在Symfony中管理Flash消息的最佳方法是什么?

时间:2019-07-24 07:17:36

标签: symfony

我正在尝试清洁控制器,我要做的一件事就是建立一种向会话FlashBag添加闪存消息的标准。

现在,按照Symfony文档的建议,我将从Controller中添加它们。

/**
 * @Route("/user/{id}/edit", name="user_edit", requirements={"id"="\d+"})
 */
public function userEdit(Request $request, User $user, UserService $userService, TranslatorInterface $translator): Response
{
    ...
    $form = $this->createForm(UserType::class, $user);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        try {
            ...
            $userService->update($user);
            $this->addFlash('success', $translator->trans('flash.update_persisted'));
        } catch (ORMException $e) {
            ...
            $this->addFlash('danger', $translator->trans('error.update_not_persisted'));
        }
    } elseif ($form->isSubmitted()) {
        ...
        $this->addFlash('danger', $translator->trans('error.validation_error'));
    }
    ...
    return $this->render('admin/users/edit.html.twig', ['user' => $user, 'form' => $form->createView()]);
}

寻找一些替代方法,我来看看FOSUserBundle实现的方法:从Event派发Controller并将Flash消息添加到EventSubscriber中。

public function editAction(Request $request)
{
    ...
    if ($form->isValid()) {
        ...
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
        return $response;
    }
    ...
}
class FlashListener implements EventSubscriberInterface
{
    private static $successMessages = array(
        ...
        FOSUserEvents::PROFILE_EDIT_COMPLETED => 'profile.flash.updated',
        ...
    );

    private $session;
    private $translator;

    public function __construct(Session $session, TranslatorInterface $translator)
    {
        $this->session = $session;
        $this->translator = $translator;
    }

    public static function getSubscribedEvents()
    {
        return array(
            ...
            FOSUserEvents::PROFILE_EDIT_COMPLETED => 'addSuccessFlash',
            ...
        );
    }

    public function addSuccessFlash(Event $event)
    {
        if (!isset(self::$successMessages[$event->getName()])) {
            throw new \InvalidArgumentException('This event does not correspond to a known flash message');
        }

        $this->session->getFlashBag()->add('success', $this->trans(self::$successMessages[$event->getName()]));
    }

    private function trans($message, array $params = array())
    {
        return $this->translator->trans($message, $params, 'FOSUserBundle');
    }
}

您认为哪一种是最佳做法?为什么?

0 个答案:

没有答案