2022 EduSoho开发手册 日常技巧之不修改文件更新系统模板
业务场景:在日常开发后,可能会修改到程序自身的模板文件,但是这些文件可能会随着系统的更新被覆盖掉。所以我们需要一个注入的方式,在不修改自身模板文件的情况下,进行代码的调整
操作方式
创建渲染视图解析器
RenderViewResolver
<?php
/*
* 作者:少宇 - 赛驰网络
* 联系:170 33333 111
* 时间:2022/2/15 上午4:23
* 网址:https://www.saichinet.com
*
* 山东赛驰网络科技有限公司
* Shandong Search Network Technology Co., Ltd.
* Copyright © 2012-2020 Search Network, All Rights Reserved
*/
namespace DiscordPlugin\Biz\Discord\Util;
use AppBundle\Component\ViewResolver\RenderViewResolver;
class DiscordRenderViewResolver implements RenderViewResolver
{
public function __construct($biz)
{
$this->biz = $biz;
}
public function generateRenderView($view, array $parameters = array())
{
if (array_key_exists($bizPrefix, $this->biz['template_extension.discord'])) {
return $this->biz["template_extension.discord"][$view];
}
return $view;
}
}
注册解析器与过滤文件
DiscordPlugin
use DiscordPlugin\Biz\Discord\Util\DiscordRenderViewResolver;
// 需要替换的模板路径
$biz['template_extension.discord'] = [
'settings/binds.html.twig' => 'DiscordPlugin:settings:binds.html.twig',
'login/oauth2-logins-block.html.twig' => 'DiscordPlugin:login:oauth2-logins-block.html.twig',
];
$biz['render_view_resolvers'] = function ($biz) {
return [
new DiscordRenderViewResolver($biz),
];
};
剖析思路
DefaultController
class DiscordController extends BaseController
public function indexAction()
{
return $this->render('DiscordPlugin:Default:index.html.twig');
}
在程序的控制内的页面输入使用的是"$this->render"方法,
BaseController
public function render($view, array $parameters = [], Response $response = null)
{
$biz = $this->getBiz();
foreach ($biz['render_view_resolvers'] as $resolver) {
$view = $resolver->generateRenderView($view, $parameters);
}
return parent::render($view, $parameters, $response);
}
页面渲染有使用到$biz['render_view_resolvers']
,我们就从$biz['render_view_resolvers']
下手
DefaultServiceProvider
$biz['render_view_resolvers'] = function ($biz) {
return [
new CourseRenderViewResolver($biz),
];
};
这是一个覆写方法
CourseRenderViewResolver
public function generateRenderView($view, array $parameters = array())
{
if (isset($parameters['course'])) {
$type = $parameters['course']['type'];
} elseif (isset($parameters['courseSet'])) {
$type = $parameters['courseSet']['type'];
} elseif (isset($parameters['params']['type'])) {
$type = $parameters['params']['type'];
} else {
return $view;
}
return DynUrlToolkit::getUrl($this->biz, $view, array('type' => $type));
}
业务判断
DynUrlToolkit
public static function getUrl($biz, $baseUrl, $params)
{
$twigSegs = explode('.html.twig', $baseUrl);
$bizPrefix = $twigSegs[0];
$type = $params['type'];
if (!empty($biz["template_extension.{$type}"]) && !empty($biz["template_extension.{$type}"][$bizPrefix])) {
return $biz["template_extension.{$type}"][$bizPrefix];
}
return $baseUrl;
}