Symfony2 重定向所有请求 [英] Symfony2 redirect all requests

查看:42
本文介绍了Symfony2 重定向所有请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法在有条件的情况下重定向所有请求.例如,如果我有一个带有 websiteDisabled = true 的实体用户.据我所知,您不能从服务重定向.还有其他办法吗?

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. As far as I know, you cannot redirect from a service. Is there any other way?

推荐答案

你想创建一个监听 kernel.request 事件的监听器(此处的文档).在该侦听器中,您可以访问请求,和容器,所以你可以做任何你喜欢的事情.在 kernel.request 期间Symfony 给你一个 GetResponseEvent.

You want to create a listener that listens to the kernel.request event (documentation here). 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.

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

You can set a Response object on this event just as you would return a response in a controller. If you do set a response, Symfony will return it and not go through the normal request --> controller --> response cycle.

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 }

这篇关于Symfony2 重定向所有请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆