如何从会话中设置默认路由参数?

时间:2013-05-14 11:49:03

标签: symfony routing

如果我有一批看起来像这样的路线:

/{location}/catalog
/{location}/search

会话始终具有“位置”属性(自动识别的用户位置的别名,例如城市)。因此,要使用{location}参数生成每个路由,我需要执行

{ location: session.get('location') }

有没有办法自动执行此操作?我可以覆盖默认的UrlGenerator并将@session注入其中吗?

2 个答案:

答案 0 :(得分:0)

尝试覆盖RoutingExtension类/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Extension/CodeExtension.php Symfony 2.1 Extending Core Classes

此外,您可以分叉https://github.com/symfony/TwigBridge并将其与作曲家http://getcomposer.org/doc/05-repositories.md#vcs

一起使用

答案 1 :(得分:0)

像这样创建一个新的EventSubscriber。 该文档类似于https://symfony.com/doc/current/session/locale_sticky_session.html

// src/EventSubscriber/LocationSubscriber.php
class LocationSubscriber implements EventSubscriberInterface 
{
    private $router;
    private $defaultLocation;

    public function __construct(string $defaultLocation = "Vigo", RequestContextAwareInterface $router = null)
    {
        $this->router          = $router;
        $this->defaultLocation = $defaultLocation;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the location has been set as a _location routing parameter
        if ($location = $request->attributes->get('_location')) {
            $request->getSession()->set('_location', $location);
        } else {
            // if no explicit location has been set on this request, use one from the session
            $location = $request->getSession()->get('_location', $defaultLocation);
        }

        // set Router Context from session
        if (null !== $this->router) {
            $this->router->getContext()->setParameter('_location', $location);
        }
    }

    public static function getSubscribedEvents(){
        return [
            // must be registered before (i.e. with a higher priority than) the default Locale listener
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }
}