如果未设置会话,则重定向特定路由

时间:2015-07-01 15:36:58

标签: php symfony routing

如果未设置会话,如何将用户重定向到主页面?这里的会话只是他们在输入字段中输入的名称。

如果我使用条件检查控制器方法中的会话,代码将重复。有没有办法像Laravel一样对路线进行分组并应用配置?

重复的代码:

 if( $this->get('session')->get('fbSession'))
        return $this->redirectToRoute('app_home');

1 个答案:

答案 0 :(得分:0)

如果要对指定路由执行此检查,可以为内核请求事件实现事件侦听器。

parameters.yml

routes_list:
    - app_messages
    - app_profile
    - app_something

的services.xml

<service id="app.session_listener" class="AppBundle\EventListener\SessionListener">
    <tag name="kernel.event_subscriber"/>
    <argument type="service" id="router"/>
    <argument>%routes_list%</argument>
</service>

SessionLisener.php

<?php

namespace AppBundle\EventListener;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\RouterInterface;

class SessionListener implements EventSubscriberInterface
{
    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @var array
     */
    private $routesList;

    /**
     * @param RouterInterface $router
     * @param array $routesList
     */
    public function __construct(RouterInterface $router, $routesList)
    {
        $this->router = $router;
        $this->routesList = $routesList;
    }

    static public function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => array(array('onKernelRequest', -50)),
        ];
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            return;
        }

        $request = $event->getRequest();
        if (! in_array($request->get('_route'), $this->routesList)) {
            return;
        }

        if ($request->getSession()->has('fbSession')) {
            $event->setResponse(new RedirectResponse($this->router->generate('app_home')));
        }
    }
}