我的情况是这样的,我想从数据库中删除一个用户记录。这很简单。但是有两种可能的结果。
1.用户已被删除
1.该用户已被FK引用,删除失败,因此,该用户被标记为禁用。(active/enabled = false)
我的想法是,对Users
实体采取的这个操作应该在UsersRepository
中,所以这就是我的方法deleteUser($user)
所在的地方。$user
是通过ParamConverter自动查询的用户对象,并传递给存储库方法。
因为工作是在存储库中完成的,所以对我来说提供反馈是有意义的。
我如何从我的App\Repository\UsersRepository extends ServiceEntityRepository
addFlash()
?或者我应该在其他地方做这个“工作”?
3条答案
按热度按时间hsgswve41#
更新:我很久以前就问过这个问题,虽然我在下面找到了工作,正如评论中指出的那样,这是一个不好的做法。
直接回答我的问题,“其他地方”是如何完成这一点。
最后,这是一个简单的一次性任务,所以所有的逻辑都在控制器中,不需要在其他地方重用。
然而,我有类似的情况,其中实体的删除更加复杂。对于这些,在控制器中创建并使用服务。操作的结果从服务传递回来,然后控制器将创建flash消息。这样,服务就不会与需要flash和会话的UI绑定。
下面的原始答案
我通过控制台
bin/console debug:autowiring
找到了FlashBagInterface
所以
Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface
的正常依赖注入你可以
$this->FlashBagInterface->add()
简单。为了回答的完整性,这里是代码;
src/Repository/UsersRepository.php(为了简洁,大多数代码都被去掉了)
envsm3lx2#
您应该从控制器添加flash消息,如官方文档所示:
https://symfony.com/doc/current/controller.html
另外,如果你是Symfony的新手,你可能想看看服务是如何工作的,因为它是你的很多工作和方法将要结束的地方。如果你使用Doctrine,在控制器中删除用户的操作应该是这样的:
这是一个有点'开箱即用',当然可以改进,但你得到的想法.我的建议是,通过一些官方文件,这是相当容易得到启动:)最终尝试通过Knp symfony 4第一课程,它是2-3小时长,相当有用
rggaifut3#
new-in-symfony-5-3-session-service-deprecation
$flashBag;