Symfony 5 (Bolt 4) 中的用户列表

问题描述

我正在使用基于 Symfony 5 的 Bolt 4 CMS。在我编写的控制器中,我想列出我数据库中的所有用户,以检索他们的电子邮件地址并向他们发送电子邮件。现在我只是想从用户名中检索电子邮件地址。

在这个例子https://symfony.com/doc/current/security/user_provider.html中,它说明了如何创建自己的类来处理来自数据库用户

// src/Repository/UserRepository.PHP
namespace App\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;

class UserRepository extends ServiceEntityRepository implements UserLoaderInterface
{
    // ...

    public function loadUserByUsername(string $usernameOrEmail)
    {
        $entityManager = $this->getEntityManager();

        return $entityManager->createquery(
                'SELECT u
                FROM App\Entity\User u
                WHERE u.username = :query
                OR u.email = :query'
            )
            ->setParameter('query',$usernameOrEmail)
            ->getoneOrNullResult();
    }
}

在我的自定义控制器中,我然后调用这个类和函数

// src/Controller/LalalanEventController.PHP
namespace App\Controller;

use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

use App\Repository\LalalanUserManager;

class LalalanEventController extends AbstractController
{
    /**
     * @Route("/new_event_email")
     */
    private function sendEmail(MailerInterface $mailer)
    {
        $userManager = new LalalanUserManager();
        
        $email = (new Email())
            ->from('aaa.bbb@ccc.com')
            ->to($userManager('nullname')->email)
            ->subject('Nice title')
            ->text('Sending emails is fun again!')
            ->html('<p>See Twig integration for better HTML integration!</p>');

        $mailer->send($email);
    }
}

不幸的是,在示例中,该类从 ServiceEntityRepository 扩展,它需要一个 ManagerRegistry 作为构造函数。有没有人知道我可以改变什么来解决这个问题?

提前致谢!

解决方法

正如文档中所说,

用户提供程序是与 Symfony Security 相关的 PHP 类,它们有两个工作:

  • 从会话中重新加载用户
  • 为某些功能加载用户

因此,如果您只想获取用户列表,只需像这样获取 UserRepository

    /**
     * @Route("/new_event_email")
     */
    private function sendEmail(MailerInterface $mailer)
    {
        $userRepository = $this->getDoctrine()->getRepository(User::class);

        $users = $userRepository->findAll();

        // Here you loop over the users
        foreach($users as $user) {
            /// Send email
        }
    }

教义参考:https://symfony.com/doc/current/doctrine.html

您还需要在此处了解有关依赖项注入的更多信息:https://symfony.com/doc/current/components/dependency_injection.html