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

时间:2016-12-09 14:38:21

标签: php symfony logout

在Symfony中,用户成功注销后,如何显示成功消息,例如"您已成功注销" ?

2 个答案:

答案 0 :(得分:4)

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)在登录页面的树枝模板中添加:

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

答案 1 :(得分:1)

Imho,有一种绝对简单的方法。在security.yaml中,使用target键,定义注销后重定向到的路由:

security:
  firewalls:
    main:
     [...]
     logout:
       path: /logout
       target: /logout_message

然后在控制器中(SecurityController.php很好),定义此操作,仅添加即显消息,然后重定向到所需位置(在此示例中为家):

/**
 * @Route("/logout_message", name="logout_message")
 */
public function logoutMessage()
{
    $this->addFlash('success', 'You've been disconnected. Bye bye !');
    return $this->redirectToRoute('home');
}