【问题标题】:How to set default route parameter from session?如何从会话设置默认路由参数?
【发布时间】:2019-10-30 23:14:17
【问题描述】:

如果我有一批如下所示的路线:

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

等等

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

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

有没有办法自动做到这一点?我可以覆盖默认的 UrlGenerator 并将@session 注入其中吗?

【问题讨论】:

  • 我有使用 twig 的解决方案。我用注入的“会话”和“路由器”定义了一个树枝扩展,并使用合并的参数创建了自定义的“location_path”函数。但我必须替换所有模板中的 path() ,这不是我认为的最佳解决方案。

标签: symfony routing


【解决方案1】:

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

您也可以 fork https://github.com/symfony/TwigBridge 并将其与 composer http://getcomposer.org/doc/05-repositories.md#vcs 一起使用

【讨论】:

  • 谢谢!可悲的是,但似乎唯一的方法是 fork TwigBridge(不可能将其他服务注入 RoutingExtension,我只能指定一个类)。所以我更喜欢替换所有路径函数。支持起来会更容易。
【解决方案2】:

像这样创建一个新的 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]],
        ];
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多