【问题标题】:Get navigationId from HttpCacheHitEvent in Shopware 6从 Shopware 6 中的 HttpCacheHitEvent 获取 navigationId
【发布时间】:2022-09-23 23:34:46
【问题描述】:

我有一个订阅者正在收听HttpCacheHitEvent,我想找到所请求页面的navigationId。

对于店面活动,我使用$event->getRequest()->getRequestUri()。但是对于这个事件,我得到了像/navigation/5943fc... 这样的 URL。我目前使用basename() 函数来获取这些URL 的navigationIds,但这似乎不是一种干净的方法。

有没有其他方法可以从 HttpCacheHitEvent 中检索 navigationId?

    标签: symfony shopware shopware6


    【解决方案1】:

    当您订阅此事件时,您无法像往常一样访问_route 和其他参数属性,因为缓存的响应将在通常设置之前返回。

    $request = $event->getRequest();
    var_dump($request->attributes->get('_route'));
    // null
    

    为了解决这个问题,您可以在注册监听器时注入router 服务。

    <service id="Foo\MyPlugin\CacheHitListener">
        <argument type="service" id="router"/>
        <tag name="kernel.event_subscriber"/>
    </service>
    

    然后,在您的侦听器中,您可以使用服务和事件中的请求对象检索您的路由参数,这样您就可以确定正在请求哪个路由。根据路线,您可以继续使用特定路线的参数。

    class CacheHitListener implements EventSubscriberInterface
    {
        private $matcher;
    
        /**
         * @param UrlMatcherInterface|RequestMatcherInterface $matcher
         */
        public function __construct($matcher)
        {
            $this->matcher = $matcher;
        }
    
        public static function getSubscribedEvents(): array
        {
            return [HttpCacheHitEvent::class => 'onCacheHit'];
        }
    
        public function onCacheHit(HttpCacheHitEvent $event): void
        {
            if ($this->matcher instanceof RequestMatcherInterface) {
                $parameters = $this->matcher->matchRequest($event->getRequest());
            } else {
                $parameters = $this->matcher->match($event->getRequest()->getPathInfo());
            }
    
            if ($parameters['_route'] === 'frontend.navigation.page') {
                $navigationId = $parameters['navigationId'];
                
                //...
            }
        }
    }
    

    【讨论】:

    • 我们尝试过,但在此事件期间属性不包含_route
    猜你喜欢
    • 2021-01-01
    • 2022-10-23
    • 2022-11-26
    • 2022-07-15
    • 2021-11-22
    • 2021-01-11
    • 2021-01-12
    • 2023-02-01
    • 2021-10-19
    相关资源
    最近更新 更多