Symfony2 - 在每条路线中调用一些动作

时间:2012-11-16 08:05:07

标签: symfony twig

我有一些事情需要在每个动作中调用,比如从我的数据库中获取标签,或者所有文章的数量等。
现在我总是在每个想要显示它的动作中触发其他功能。有没有办法解雇一些函数而不在适合当前路径的行动中触发它们,并在这些函数中分配一些树枝变量?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

  • 创建一个全局“假”操作,接受特定“类型”的每个请求
  • 定义一个动作调度程序(作为服务),它将路由到正确的操作(或用户$router symfony2对象,只要您将路径名称作为参数准确传递给您的“假” “行动
  • 在调用正确的操作后,执行您需要执行的所有操作

所以,像这样

public function actionDispatcher(Request $request, $route_name, $parameters)
{
   /* retrieve the router */
   $router = $this->get('router');
   $myRouteDefaultsArray = $router->getRouteCollection->get('route_name')->getDefaults();
   /* retrieve the correct action */
   $myAction = $myRouteDefaultsArray['_controller'];
   /*use your action here */
   [.....]
   /* fire your functions here */
   [.....]
   /* render the twig template along your variables here */
   [.....]
}

}

答案 1 :(得分:2)

感谢DonCallisto,我做到了这一点:

<?php

namespace Puzzle\InfobusBundle\EventListener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;

class MyListener{
    protected $doctrine;
    protected $templating;
    protected $session;
    protected $container;


    /**
     * @param ContainerInterface $container
     */
    public function __construct($security, $doctrine, $session, $templating, $container){
        $this->doctrine=$doctrine;
        $this->session=$session;
        $this->templating=$templating;
        $this->container=$container;
    }

    public function onKernelRequest() {
        $this->container->get('twig')->addGlobal('myVar', 1234);
    }

在app / config / config.yml中:

services:
    acme_my.exception.my_listener:
        class: Acme\MyBundle\EventListener\MyListener
        arguments: ["@security.context", "@doctrine", "@session", "@templating", "@service_container"]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

现在onKernelRequest中的代码会在每个页面上触发代码,我可以将一些变量发送到twig模板。