symfony - 具有全局树枝服务的基类控制器
问题描述
首先,我不得不说我已经看了几天的答案和文档,但没有一个回答我的问题。
我想做的唯一且简单的事情是使用 twig 服务作为 BaseController 中的全局服务。
这是我的代码:
<?php
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Service\Configuration;
use App\Utils\Util;
abstract class BaseController extends Controller
{
protected $twig;
protected $configuration;
public function __construct(\Twig_Environment $twig,Configuration $configuration)
{
$this->twig = $twig;
$this->configuration = $configuration;
}
}
然后在我所有的控制器中扩展树枝和配置服务,而不必一次又一次地注入它。
//...
//......
/**
* @Route("/configuration", name="configuration_")
*/
class ConfigurationController extends BaseController
{
public function __construct()
{
//parent::__construct();
$this->twig->addGlobal('menuActual', "config");
}
正如您所看到的,我唯一想要的就是拥有一些services
全局性以使一切更有条理,并shortcuts
为我所有的controllers
. 在此示例中,我分配了一个全局变量以使链接在我的模板菜单中处于活动状态,并且在每个控制器中我必须为 . 添加一个新值menuActual
,例如在UserController
变量中为addGlobal('menuActual', "users")
.
我认为这应该是我找不到的 symfony 的良好做法:(。
必须在每个控制器中包含\Twig_Environment
以将变量分配给视图对我来说似乎非常重复。这应该默认出现在控制器中。
谢谢
解决方案
我也遇到过这个问题 - 试图不必为每个控制器/动作重复一些代码。
我使用事件侦听器解决了它:
# services.yaml
app.event_listener.controller_action_listener:
class: App\EventListener\ControllerActionListener
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
#src/EventListener/ControllerActionListener.php
namespace App\EventListener;
use App\Controller\BaseController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
/**
* Class ControllerActionListener
*
* @package App\EventListener
*/
class ControllerActionListener
{
public function onKernelController(FilterControllerEvent $event)
{
//fetch the controller class if available
$controllerClass = null;
if (!empty($event->getController())) {
$controllerClass = $event->getController()[0];
}
//make sure your global instantiation only fires if the controller extends your base controller
if ($controllerClass instanceof BaseController) {
$controllerClass->getTwig()->addGlobal('menuActual', "config");
}
}
}
推荐阅读
- wordpress - Wordpress 重写规则以创建漂亮的 URL
- python - Python:如何获取具有名称列表、两列格式的导入文本文件,并将它们按字母顺序放入 python 中?
- verilog - 不支持在表达式中使用时钟信号
- java - 在 Java BufferedImage 中应用桶形失真校正,但结果相当混乱
- android - 为什么我的带有 Dagger2 实现的 DI 崩溃了?
- ios - 使用以前使用的模板提交 Apple iOS 应用程序
- reactjs - 为什么编译器警告未定义?
- c# - 如何使用约束使多个按钮居中?
- python - 如何聚合任意键组的查询集
- matlab - 如何根据值的符号确定四个随机案例中的哪一个并计算它需要多少次?