首页 > 解决方案 > 具有全局树枝服务的基类控制器

问题描述

首先,我不得不说我已经看了几天的答案和文档,但没有一个回答我的问题。

我想做的唯一且简单的事情是使用 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以将变量分配给视图对我来说似乎非常重复。这应该默认出现在控制器中。

谢谢

标签: symfony

解决方案


我也遇到过这个问题 - 试图不必为每个控制器/动作重复一些代码。

我使用事件侦听器解决了它:

# 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");
        }
    }
}

推荐阅读