如何解决控制器 Symfony 2 外的 Doctrine 查询
两天以来,我在使用控制器外的 UserRepository 进行查询时遇到了一些麻烦。我试图从我命名为 ApiKeyAuthenticator 的类中从数据库中获取用户。我想在函数 getUsernameForApiKey 中执行查询,就像在文档中一样。我想我应该使用 donctrine 作为服务,但我不知道如何做到这一点。
提前感谢您的帮助!
<?php
// src/AppBundle/Security/ApiKeyUserProvider.php
namespace AppBundle\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class ApiKeyUserProvider implements UserProviderInterface
{
public function getUsernameForApiKey($apiKey)
{
// Look up the username based on the token in the database,via
// an API call,or do something entirely different
$username = ...;
return $username;
}
public function loadUserByUsername($username)
{
return new User(
$username,null,// the roles for the user - you may choose to determine
// these dynamically somehow based on the user
array('ROLE_API')
);
}
public function refreshUser(UserInterface $user)
{
// this is used for storing authentication in the session
// but in this example,the token is sent in each request,// so authentication can be stateless. Throwing this exception
// is proper to make things stateless
throw new UnsupportedUserException();
}
public function supportsClass($class)
{
return User::class === $class;
}
}
解决方法
您必须将 ApiKeyUserProvider
设为服务并将 UserRepository
作为依赖项注入。不确定存储库是否是 2.8 中的服务,因此您可能必须注入 EntityManager
.
class ApiKeyUserProvider implements UserProviderInterface
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function loadUserByUsername($username)
{
$repository = $this->em->getRepository(User::class);
// ...
现在将您的类注册为 services.yml 文件中的服务
services:
app.api_key_user_provider:
class: AppBundle\Security\ApiKeyUserProvider
arguments: ['@doctrine.orm.entity_manager']
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。