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

List of users in Symfony 5 (Bolt 4)

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

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

// 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();
    }
}

在我的自定义控制器中,我调用这个 class 和函数:

// 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);
    }
}

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

提前致谢!

如文档中所述,

User providers are PHP classes related to Symfony Security that have two jobs:

  • Reload the User from the Session
  • Load the User for some Feature

因此,如果您只想获取用户列表,您只需像这样获取 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