gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:25:58 26 4
gpt4 key购买 nike

功能 getCurrentOrDefaultLocale() ,在我的服务中定义,可以从 Controller 或通过命令行脚本调用。

访问 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();
}

最佳答案

您可以简单地检查当前容器实例是否有 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;
}
}
剪下的这段代码来自我自己的项目,在那里我遇到了一个非常相似的问题。

关于session - 检测是否可以在 Symfony 2 中访问请求服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com