Symfony:注销后如何显示成功消息

Fra*_*rzi 5 php logout symfony

在Symfony中,用户成功登出后,如何显示“您已成功登出”之类的成功信息?

Fra*_*rzi 6

1) 创建一个新的服务来处理注销成功事件。

services.yml添加服务:

logout_success_handler:
    class: Path\To\YourBundle\Services\LogoutSuccessHandler
    arguments: ['@security.http_utils']
Run Code Online (Sandbox Code Playgroud)

并添加类,替换/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;
    }
}
Run Code Online (Sandbox Code Playgroud)

2)配置您security.yml使用LogoutSuccessHandler刚刚创建的自定义:

firewalls:
    # ...
    your_firewall:
        # ...
        logout:
            # ...
            success_handler: logout_success_handler
Run Code Online (Sandbox Code Playgroud)

3)在登录页面的树枝模板中添加:

{% if app.request.get('logout') == "success" %}
    <p>You have successfully logged out!</p>
{% endif %}
Run Code Online (Sandbox Code Playgroud)


Al *_* ѫ 6

恕我直言,有一种绝对更简单的方法。在 中security.yaml,通过targetkey定义注销后重定向到的路由:

security:
  firewalls:
    main:
     [...]
     logout:
       path: /logout
       target: /logout_message
Run Code Online (Sandbox Code Playgroud)

然后在控制器中(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');
}
Run Code Online (Sandbox Code Playgroud)