Symfony2重定向所有请求

men*_*lic 1 redirect symfony

我想知道如果有条件,是否有办法重定向所有请求.例如,如果我有一个具有websiteDisabled = true的实体User.据我所知,您无法从服务重定向.还有其他方法吗?

Pet*_*ell 5

您想要创建一个侦听kernel.request事件的侦听器(此处的文档).在该侦听器中,您可以访问请求和容器,以便您可以执行任何您喜欢的操作.在kernel.request Symfony给你一个GetResponseEvent.

您可以Response在此事件上设置对象,就像在控制器中返回响应一样.如果您确实设置了响应,Symfony将返回它,而不是通过正常请求 - >控制器 - >响应周期.

namespace Acme\UserBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\DependencyInjection\ContainerAware;

class UserRedirectListener extends ContainerAware
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            // don't do anything if it's not the master request
            return;
        }

        $user = $this->container->get('security.context')->getToken()->getUser();

        // for example...
        if ($user->websiteDisabled === false) {
            return;
        }

        // here you could render a template, or create a RedirectResponse
        // or whatever it is
        $response = new Response();

        // as soon as you call GetResponseEvent#setResponse
        // symfony will stop propogation and return the response
        // no other framework code will be executed
        $event->setResponse($response);
    }
}
Run Code Online (Sandbox Code Playgroud)

您还需要在一个配置文件中注册事件侦听器,例如:

# app/config/config.yml
services:
    kernel.listener.your_listener_name:
        class: Acme\UserBundle\EventListener\UserRedirectListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Run Code Online (Sandbox Code Playgroud)