简体   繁体   English

Symfony2重定向所有请求

[英]Symfony2 redirect all requests

I would like to know if there is a way to redirect all requests if there is a condition. 我想知道如果有条件的话是否可以重定向所有请求。 For example, if I have an entity User with websiteDisabled = true. 例如,如果我有一个实体用户,其websiteDisabled = true。 As far as I know, you cannot redirect from a service. 据我所知,您不能从服务重定向。 Is there any other way? 还有其他办法吗?

You want to create a listener that listens to the kernel.request event ( documentation here ). 您想要创建一个侦听kernel.request事件的侦听器( 此处提供文档 )。 In that listener you have access to the request, and the container so you can do anything you like. 在该侦听器中,您可以访问请求和容器,因此您可以执行任何您喜欢的事情。 During kernel.request Symfony gives you a GetResponseEvent . kernel.request期间,Symfony为您提供了GetResponseEvent

You can set a Response object on this event just as you would return a response in a controller. 您可以在此事件上设置Response对象,就像在控制器中返回响应一样。 If you do set a response, Symfony will return it and not go through the normal request --> controller --> response cycle. 如果您确实设置了响应,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);
    }
}

You will also need to register the event listener in one of your config files, for example: 您还需要在一个配置文件中注册事件监听器,例如:

# 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM