You need to enable JavaScript to run this app. Symfony 2 如何在控制器外部使用Doctrine调用UserRepository执行查询
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 2 如何在控制器外部使用Doctrine调用UserRepository执行查询

实现步骤
  • 第一步:修改ApiKeyUserProvider类,注入Doctrine依赖,补充对应逻辑
    修改后的完整代码如下:
<?php
// src/AppBundle/Security/ApiKeyUserProvider.php
namespace AppBundle\Security;
    
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Doctrine\ORM\EntityManagerInterface;
// 替换为你自己项目中User实体的命名空间
use AppBundle\Entity\User as AppUser;

class ApiKeyUserProvider implements UserProviderInterface
{
    private $entityManager;

    // 构造函数注入EntityManager
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function getUsernameForApiKey($apiKey)
    {
        // 通过UserRepository查询匹配apiKey的用户
        $user = $this->entityManager->getRepository(AppUser::class)
            ->findOneBy(['apiKey' => $apiKey]);
        
        if (null === $user) {
            return null;
        }

        return $user->getUsername();
    }

    public function loadUserByUsername($username)
    {
        $user = $this->entityManager->getRepository(AppUser::class)
            ->findOneBy(['username' => $username]);
        
        if (null === $user) {
            throw new UsernameNotFoundException(sprintf('用户 %s 不存在', $username));
        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        throw new UnsupportedUserException();
    }

    public function supportsClass($class)
    {
        // 适配你自己的User实体类
        return AppUser::class === $class || is_subclass_of($class, AppUser::class);
    }
}
  • 第二步:配置服务依赖
    如果你的项目开启了Symfony自动装配(3.4及以上版本默认开启),无需额外配置,框架会自动注入EntityManager到该类。
    如果未开启自动装配,需要在服务配置文件app/config/services.yaml中添加如下配置:
services:
    AppBundle\Security\ApiKeyUserProvider:
        arguments:
            $entityManager: '@doctrine.orm.entity_manager'
  • 可选优化:如果你的项目有自定义的UserRepository,也可以直接注入UserRepository替代EntityManager,逻辑和注入方式完全一致,仅需要修改构造函数的参数类型即可。

内容的提问来源于stack exchange,提问作者Redjy Redj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 07:36:03