Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 get current environment in response listener

Tags:

symfony

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.

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:

services:
   my.listener:
       class: Path\To\Listener
       tags:
           - { name: kernel.event_listener, event: kernel.response }
       arguments: [@kernel]
like image 692
ojreadmore Avatar asked May 07 '12 17:05

ojreadmore


1 Answers

$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.

like image 152
Mun Mun Das Avatar answered Nov 07 '22 21:11

Mun Mun Das