Symfony 3.1可以访问数据库的监听器

时间:2016-08-09 09:39:54

标签: symfony

我有一个带有'web_enabled'键的配置表,如果为true我想显示请求的路由但是当我想要显示'维护中的站点'页面时。显然,必须在任何路线行动之前执行此检查。

我一直在阅读有关事件和听众的内容,但我没有看到如何实现对学说和模板的访问。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这是我最终实现的解决方案,与Alsatian提出的解决方案不同,因为我没有在service.yml中使用参数。只是一个品味的问题,没有别的。

app / config / services.yml

def context = application.mainContext.servletContext

在src / AppBundle / EventListener / RequestListener.php

services:
app.request_listener:
    class: AppBundle\EventListener\RequestListener
    arguments: ["@doctrine.orm.entity_manager","@templating"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelController }

并在src / AppBundle / Repository / ConfigRepository.php中解释getconfig方法:

namespace AppBundle\EventListener;

use \Symfony\Component\HttpKernel\Event\GetResponseEvent;
use \Symfony\Component\HttpFoundation\Response;

class RequestListener
{
    private $em;
    private $templating;

    public function __construct($em, $templating)
    {
       $this->em = $em;
       $this->templating = $templating;
    }

    public function onKernelController(GetResponseEvent $event)
    {
        if ( !$this->configKey = $this->em->getRepository('AppBundle:Config')->getconfig('web_enabled') )
            $event->setResponse($this->templating->renderResponse('default/construction.html.twig'));

    }
}

}

希望这有帮助。

答案 1 :(得分:0)

您只需在侦听器中注入EntityManager和Templating:

定义为服务:

# src/AppBundle/Ressources/config/services.yml
services:
    app.request_listener:
        class: AppBundle\EventListener\RequestListener
        arguments: ["%web_enabled%","@doctrine.orm.entity_manager","@templating"]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

听众:

namespace AppBundle\EventListener;

use \Symfony\Component\HttpKernel\Event\GetResponseEvent;
use \Symfony\Component\HttpFoundation\Response;

class RequestListener
{
    private $configKey;
    private $em;
    private $templating;

    public __construct($configKey, $em, $templating)
    {
        $this->configKey = $configKey;
        $this->em = $em;
        $this->templating = $templating;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if(!$this->configKey){
            $var = $this->em->getRepository('AppBundle:MyEntity')->findOne(1);

            $event->setResponse($this->templating->renderResponse('my_template.html.twig',array('var'=>$var));
        }
    }
}