Symfony 4,flash消息从仓库或其他地方?

ruarlubt  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(102)

我的情况是这样的,我想从数据库中删除一个用户记录。这很简单。但是有两种可能的结果。
1.用户已被删除
1.该用户已被FK引用删除失败,因此,该用户被标记为禁用。(active/enabled = false)
我的想法是,对Users实体采取的这个操作应该在UsersRepository中,所以这就是我的方法deleteUser($user)所在的地方。$user是通过ParamConverter自动查询的用户对象,并传递给存储库方法。
因为工作是在存储库中完成的,所以对我来说提供反馈是有意义的。
我如何从我的App\Repository\UsersRepository extends ServiceEntityRepositoryaddFlash()?或者我应该在其他地方做这个“工作”?

hsgswve4

hsgswve41#

更新:我很久以前就问过这个问题,虽然我在下面找到了工作,正如评论中指出的那样,这是一个不好的做法。
直接回答我的问题,“其他地方”是如何完成这一点。
最后,这是一个简单的一次性任务,所以所有的逻辑都在控制器中,不需要在其他地方重用。
然而,我有类似的情况,其中实体的删除更加复杂。对于这些,在控制器中创建并使用服务。操作的结果从服务传递回来,然后控制器将创建flash消息。这样,服务就不会与需要flash和会话的UI绑定。

下面的原始答案

我通过控制台bin/console debug:autowiring找到了FlashBagInterface
所以Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface的正常依赖注入
你可以$this->FlashBagInterface->add()简单。
为了回答的完整性,这里是代码;
src/Repository/UsersRepository.php(为了简洁,大多数代码都被去掉了)

<?php

namespace App\Repository;

// use ...
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;

// ...

class UsersRepository extends ServiceEntityRepository
{

    private $security;
    private $request;
    private $flash;

    public function __construct(RegistryInterface $registry, Security $security, RequestStack $request, FlashBagInterface $flash)
    {
        parent::__construct($registry, Users::class);
        $this->security = $security;
        $this->request = $request;
        $this->flash = $flash;
    }

    // ...

    /**
     * deleteUser
     *
     * @param Users $user
     * @return void
     */
    public function deleteUser($user)
    {
        $em = $this->getEntityManager();
        $user->setEnabled(false);
        $em->flush();
        try {
            $em->remove($user);
            $em->flush();
            $this->flash->add('notice', 'user.manager.user.deleted');
        } catch (ForeignKeyConstraintViolationException $e) {
            $this->flash->add('notice', 'user.manager.user.can.not.delete.disabled');
        }
    }
}
envsm3lx

envsm3lx2#

您应该从控制器添加flash消息,如官方文档所示:
https://symfony.com/doc/current/controller.html
另外,如果你是Symfony的新手,你可能想看看服务是如何工作的,因为它是你的很多工作和方法将要结束的地方。如果你使用Doctrine,在控制器中删除用户的操作应该是这样的:

MyAction(User $user){

    $em = $this->getDoctrine()->getManager();
    $em->remove($user);
    $em->flush();

    $this->addFlash(
        'notice',
        'Your user is now deleted!'
    );
   return $this->redirectToRoute('some_other_route');
}

这是一个有点'开箱即用',当然可以改进,但你得到的想法.我的建议是,通过一些官方文件,这是相当容易得到启动:)最终尝试通过Knp symfony 4第一课程,它是2-3小时长,相当有用

rggaifut

rggaifut3#

new-in-symfony-5-3-session-service-deprecation
$flashBag;

public function __construct(
          private RequestStack $requestStack,
)
{
    $this->flashBag = $this->requestStack->getSession()->getFlashBag();

}
        $this->flashBag->add('notice', 'massage');

相关问题