Accessing the AppKernel environment variable in symfony 2
It's also possible to get that as a parameter. If you take a look at the \Symfony\Component\HttpKernel\Kernel
class you'll find a getKernelParameters()
method that exposes all the kernel parameters.
/**
* Returns the kernel parameters.
*
* @return array An array of kernel parameters
*/
protected function getKernelParameters()
{
$bundles = array();
foreach ($this->bundles as $name => $bundle) {
$bundles[$name] = get_class($bundle);
}
return array_merge(
array(
'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
'kernel.environment' => $this->environment,
'kernel.debug' => $this->debug,
'kernel.name' => $this->name,
'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
'kernel.bundles' => $bundles,
'kernel.charset' => $this->getCharset(),
'kernel.container_class' => $this->getContainerClass(),
),
$this->getEnvParameters()
);
}
So in a services.yml
file you can get the environment with %kernel.environment%
whilst in a container aware class you can get it by doing:
$this->getContainer()->getParameter('kernel.environment');
see Kernel.php class on github
The default entity classes generated by the console don't inherit anything. This means they aren't "ContainerAware" in any way.
And generally speaking, I don't think they should be. I supposed it depends on what you're doing but you could handle this with some basic dependency injection
In a controller:
$entity = new \Your\Bundle\Entity\Foo(
$this->container->get( 'kernel' )->getEnvironment()
);
And then in src/Your/Bundle/Entity/Foo.php
private $env;
public function __construct( $env=null )
{
$this->env = $env;
}
Would this work for you?
P.S. The event listener you posted about is for Controllers - not for arbitrary classes.