Function getCurrentOrDefaultLocale()
, defined in my service, may be invoked from a controller or through a command line script.
Accessing request
service from CLI throws an exception, and I'm using it to detect the CLI invocation. However catching an exception only for this purpose seems so bad to me.
Is there any reliable way to check if request is accessible in the currenct context (of execution, browser vs CLI)?
/**
* @return string
*/
protected function getCurrentOrDefaultLocale()
{
try {
$request = $this->container->get('request');
}
catch(InactiveScopeException $exception) {
return $this->container->getParameter('kernel.default_locale');
}
// With Symfony < 2.1.0 current locale is stored in the session
if(version_compare($this->sfVersion, '2.1.0', '<')) {
return $this->container->get('session')->getLocale();
}
// Symfony >= 2.1.0 current locale from the request
return $request->getLocale();
}
You could simply check whether current container instance has request
service/scope using ContainerInterface::has()
/ContainerInterface::hasScope()
.
My mistake. You have to use ContainerInterface::isScopeActive()
, to determine whether request
service is fully functional:
public function __construct(ContainerInterface $container, RouterInterface $router) {
if ($container->isScopeActive('request')) {
$this->request = $container->get('request');
$this->router = $router;
}
}
This code snipped is from my own project, where I've experienced a very similar issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With