检测Symfony 2中是否可以访问请求服务?

gre*_*emo 4 session locale request symfony symfony-2.1

getCurrentOrDefaultLocale()可以从控制器或命令行脚本调用在我的服务中定义的函数.

request从CLI 访问服务会引发异常,我正在使用它来检测CLI调用.然而,仅为此目的捕获异常对我来说似乎很糟糕.

有没有可靠的方法来检查请求是否可以在当前上下文中执行(执行,浏览器与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();
}
Run Code Online (Sandbox Code Playgroud)

Cro*_*zin 8

您可以request使用ContainerInterface::has()/ 来检查当前容器实例是否具有服务/范围ContainerInterface::hasScope().

编辑:

我的错.您必须使用ContainerInterface::isScopeActive(),以确定request服务是否完全正常运行:

public function __construct(ContainerInterface $container, RouterInterface $router) {
    if ($container->isScopeActive('request')) {
        $this->request = $container->get('request');
        $this->router = $router;
    }
}
Run Code Online (Sandbox Code Playgroud)

剪切的代码来自我自己的项目,在那里我遇到了一个非常类似的问题.