首页 > 解决方案 > 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构造函数的 a。有谁知道我可以改变什么来解决这个问题?

提前致谢!

标签: phpsymfonysymfony5bolt-cms

解决方案


正如文档中所说,

用户提供者是与 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


推荐阅读