Symfony2 - 在每条路线中调用一些动作 [英] Symfony2 - call some actions in each route

查看:19
本文介绍了Symfony2 - 在每条路线中调用一些动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在每个操作中调用一些东西,例如从我的数据库中获取标签,或所有文章的数量等.
现在我总是在我想要展示的每个动作中触发其他函数.有什么方法可以触发一些函数而不触发它们适合当前路线的动作,并在这些函数中分配一些树枝变量?

I have some things that I have to call in each action, like getting tags from my DB, or number of all articles, etc.
Now I always fire other function in each action where I want to show it. Is there any way to fire some functions without firing them in action which fits to the current route, and assign some twig vars in those functions?

推荐答案

感谢 DonCallisto 我做了这个:

Thanks to DonCallisto I made this:

<?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 中:

And in 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 模板.

Now code in onKernelRequest fires code on each page, and I can send some vars to twig template.

这篇关于Symfony2 - 在每条路线中调用一些动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆