0

我正在尝试从 Symfony 2.1 迁移到 2.2.1 版本。我使用自己的选民来决定是否授予用户访问给定路线的权限。Voter 非常简单,并且在更新之前就可以使用。问题是选民需要请求服务来获取检查用户是否可以访问站点所需的参数(它是路由中给出的一些 id,例如 /profile/show/{userId})。我总是检查请求范围是否处于活动状态,以防止在使用 CLI 或 PHPUnit 时出错:

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

如果 Vote 方法中没有请求,则稍后抛出异常:

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

每次投票后我都会收到此异常(= 在我的应用程序的每个页面上)。

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

4

1 回答 1

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");
    }
}
于 2013-05-14T08:29:57.683 回答