2013-05-09 34 views
0

我试图从Symfony 2.1迁移到版本2.2.1。我使用我自己的选民来决定是否允许用户访问给定的路线。选民是非常简单的,它在更新之前工作。 问题是选民需求请求服务获取检查用户是否可以访问网站所需的参数(它是路由中给出的某个ID,例如/ profile/show/{userId})。 我经常检查,如果请求范围内使用CLI或PHPUnit的时候被激活,以防止错误:Symfony 2.2 - 请求范围在选民

$this->request = null; 
if ($container->isScopeActive('request')) { 
    $this->request = $container->get('request'); 
} 

后来又抛出一个异常,如果在投票方法没有请求:

if ($this->request === null) { 
    throw new \RuntimeException("There's no request in ProfileVoter"); 
} 

我得到这个例外每次投票后(=我的应用程序的每一页)。

编辑:它只发生在开发环境。

+0

您确定您位于请求范围内吗?另请参见:http://symfony.com/doc/master/cookbook/service_container/scopes.html – 2013-05-09 12:46:51

+0

我确定我不在请求范围内(这就是为什么我得到了这个异常),但是我没有知道为什么。我不能在我的Voter服务定义中使用_scope = request_,因为安全服务不会使用我认为的范围。更新Symfony的依赖关系后,我没有做任何更改。 – Michal 2013-05-09 13:10:35

+0

你读过链接了吗?它讨论了3种解决方法,其中一种解决方案 – 2013-05-09 13:18:44

回答

1

根据做Symfony2.2文档:

“注意不要存储在该服务的未来调用该对象的属性的请求,因为这将导致在第一部分中描述的相同问题(除了Symfony无法检测到你错了)。“ (http://symfony.com/doc/current/cookbook/service_container/scopes.html#using-a-service-from-a-narrower-scope

在您的解决方案中,您检查构造函数中的容器作用域活动,如果您有活动作用域,请将其存储在$ this-> request中。 然而,正确的方法是将不要求,但容器本身:

protected $container; 
public function __construct(ContainerInterface $container) 
{ 
    $this->container = $container; 
} 

的后面,在你的方法(正如你看到的,而不是在构造函数),检查的范围活动:

public function vote(...) 
{ 
    if ($this->container->isScopeActive('request')) { 
     $request = $this->container->get('request'); 
    } else { 
     throw new \RuntimeException("There's no request in ProfileVoter"); 
    } 
} 
+0

我的误解,这个解决方案有效,谢谢。 – Michal 2013-05-14 08:34:32