Symfony2:如何在控制器中检索UserChecker?

时间:2012-09-19 06:53:57

标签: authentication symfony symfony-2.1

Symfony2 中的UserChecker是用户身份验证的必要类。

假设您需要在控制器内部对用户进行身份验证,您应该定义如下函数:

protected function authenticateUser(User $user) {                
   $user_checker = ...//Get here the user checker
    try {
        $user_checker->checkPostAuth($user);
    } catch (AccountStatusException $e) {
        return;
    }

    $providerKey = $this->container->getParameter('firewall_name');
    $token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
    $this->container->get('security.context')->setToken($token);   
}

请注意,UserChecker在Symfony2中被定义为非公共服务:

  <service id="security.user_checker" class="%security.user_checker.class%" public="false" />

如何在控制器中获取UserChecker

提前致谢

1 个答案:

答案 0 :(得分:4)

您可以使用别名“获取”私人服务。参见:

http://symfony.com/doc/current/components/dependency_injection/advanced.html