php - 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。有谁知道我可以改变什么来解决这个问题?
提前致谢!
解决方案
正如文档中所说,
用户提供者是与 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
推荐阅读
- python - 用 python 在 Discord 上标记某人
- php - 使用 Maatwebsite / Laravel-Excel 导出带有超链接的合并单元格的 Excel
- python - 使用 python sdk 创建 vnet 和子网
- google-sheets-formula - 使用 Google 电子表格中的 importxml 提取参展商列表(公司名称)
- azure - 为 Apache Beam 批处理推荐适当的 azure 服务
- python - 在python中创建目录
- vmware - vmware 定制特定命令将存储在 Windows 机器中的什么位置?
- sql-server - SQL 参数 - T-SQL
- haproxy - Haproxy - 从请求中读取 ToS/DSCP 值
- python-3.x - 如何从热图像中检测温度热点