我正在尝试清洁控制器,我要做的一件事就是建立一种向会话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');
}
}
您认为哪一种是最佳做法?为什么?