首先,我不得不说我已经看到了几天的答案和文档,但没有一个回答我的问题。
我想做的唯一简单的事情是将 twig 服务用作 BaseController 中的全局服务。
这是我的代码:
<?php
namespace AppController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SymfonyBundleFrameworkBundleControllerController;
use AppServiceConfiguration;
use AppUtilsUtil;
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
,以使一切更有条理,并为我的所有controllers
创建一些全局shortcuts
。在此示例中,我分配了一个全局变量以使链接在我的模板菜单中处于活动状态,并且在每个控制器中,我必须为menuActual
添加一个新值,例如,在变量addGlobal('menuActual', "users")
UserController
。
我认为这应该是symfony的良好实践,但我找不到:(。
必须在每个控制器中包含Twig_Environment
才能为视图分配变量对我来说似乎非常重复。默认情况下,这应该在控制器中出现。
谢谢
我也遇到了这个问题 - 试图不必为每个控制器/操作重复一些代码。
我使用事件侦听器解决了它:
# services.yaml
app.event_listener.controller_action_listener:
class: AppEventListenerControllerActionListener
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
#src/EventListener/ControllerActionListener.php
namespace AppEventListener;
use AppControllerBaseController;
use SymfonyComponentHttpKernelEventFilterControllerEvent;
/**
* Class ControllerActionListener
*
* @package AppEventListener
*/
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");
}
}
}