Symfony2在响应侦听器中获取当前环境

时间:2022-09-24 06:47:23

I'd like to know if I'm using app_dev.php from within a listener (set up as a service in config.yml). It fails at getEnvironment() though this is the method I use in the controller.

我想知道我是否在侦听器中使用app_dev.php(在config.yml中设置为服务)。它在getEnvironment()失败,尽管这是我在控制器中使用的方法。

public function onKernelResponse(FilterResponseEvent $event) {
    $kernel = $event->getKernel();
    $this->isAppDev = ($kernel->getEnvironment() == "dev") ? true : false;
}

Edit Solution: In my listener class:

编辑解决方案:在我的监听器类中:

use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Kernel;
private $kernel;
public function __construct(Kernel $kernel) {
    $this->kernel = $kernel
}
public function onKernelResponse(FilterResponseEvent $event) {
    $this->isAppDev = ($this->kernel->getEnvironment() == "dev") ? true : false;
}

At the bottom of config.yml:

在config.yml的底部:

services:
   my.listener:
       class: Path\To\Listener
       tags:
           - { name: kernel.event_listener, event: kernel.response }
       arguments: [@kernel]

1 个解决方案

#1


19  

$event->getKernel() returns an object which implements HttpKernelInterface. Whereas Kernel or AppKernel implements KernelInterface which have getEnvironment method. You have to inject @kernel service in your listener.

$ event-> getKernel()返回一个实现HttpKernelInterface的对象。而Kernel或AppKernel实现了具有getEnvironment方法的KernelInterface。你必须在你的监听器中注入@kernel服务。

#1


19  

$event->getKernel() returns an object which implements HttpKernelInterface. Whereas Kernel or AppKernel implements KernelInterface which have getEnvironment method. You have to inject @kernel service in your listener.

$ event-> getKernel()返回一个实现HttpKernelInterface的对象。而Kernel或AppKernel实现了具有getEnvironment方法的KernelInterface。你必须在你的监听器中注入@kernel服务。