控制器 Symfony 2 外的学说查询

Doctrine query outside the controller Symfony 2

这两天我在控制器外使用 UserRepository 进行查询时遇到了一些麻烦。我正在尝试从我命名为 ApiKeyAuthenticator 的 class 数据库中获取用户。我想像文档中那样在函数 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);
        // ...


现在将您的 class 注册为 services.yml 文件中的服务

services:
    app.api_key_user_provider:
        class:     AppBundle\Security\ApiKeyUserProvider
        arguments: ['@doctrine.orm.entity_manager']