在Symfony中,用户成功注销后,如何显示“您已成功注销”之类的成功消息?
1)创建一个新服务来处理注销成功事件。
在
services.yml
中添加服务:
logout_success_handler:
class: Path\To\YourBundle\Services\LogoutSuccessHandler
arguments: ['@security.http_utils']
并添加类,将
/path/to/your/login
替换为登录页面的 url(在控制器的最后一行):
<?php
namespace Path\To\YourBundle\Services;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
protected $httpUtils;
protected $targetUrl;
/**
* @param HttpUtils $httpUtils
*/
public function __construct(HttpUtils $httpUtils)
{
$this->httpUtils = $httpUtils;
$this->targetUrl = '/path/to/your/login?logout=success';
}
/**
* {@inheritdoc}
*/
public function onLogoutSuccess(Request $request)
{
$response = $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
return $response;
}
}
2) 配置您的
security.yml
以使用刚刚创建的自定义 LogoutSuccessHandler
:
firewalls:
# ...
your_firewall:
# ...
logout:
# ...
success_handler: logout_success_handler
3)在登录页面的twig模板中添加:
{% if app.request.get('logout') == "success" %}
<p>You have successfully logged out!</p>
{% endif %}
恕我直言,有一个绝对更简单的方法。在
security.yaml
中,定义注销后通过 target
键重定向到的路由:
security:
firewalls:
main:
[...]
logout:
path: /logout
target: /logout_message
然后在控制器中(
SecurityController.php
就可以了),定义此操作,仅添加 Flash 消息,然后重定向到您想要的位置(本例中为 home):
/**
* @Route("/logout_message", name="logout_message")
*/
public function logoutMessage()
{
$this->addFlash('success', "You've been disconnected. Bye bye !");
return $this->redirectToRoute('home');
}
这是注销后显示即时消息的好方法。但有时某人注销的原因有多种。那么有没有办法在注销后截断消息?