Home > Net >  How to get or create Context in HttpCacheHitEvent subscriber?
How to get or create Context in HttpCacheHitEvent subscriber?

Time:09-27

I have a subscriber class subscribing to HttpCacheHitEvent. I want to extract context specific data from other objects. I have been using Context::createDefaultContext() before, but that does not account different parameters of the request such as the locale.

Whats the best way to get or create a context from HttpCacheHitEvent?

CodePudding user response:

You have to start the session, grab the token of it and resolve than the Context using SalesChannelContextFactory.

I cannot recommend doing this as it will make the HttpCache much slower. Maybe you can set cookies to the browser and use them there?

CodePudding user response:

You can inject the service SalesChannelRequestContextResolver and use it in combination with the router service to assemble a SalesChannelContext (and subsequently the Context) from the resolved Request.

<service id="Foo\MyPlugin\CacheHitListener">
    <argument type="service" id="router"/>
    <argument type="service" id="Shopware\Core\Framework\Routing\SalesChannelRequestContextResolver"/>
    <tag name="kernel.event_subscriber"/>
</service>
class CacheHitListener implements EventSubscriberInterface
{
    private $matcher;

    private RequestContextResolverInterface $contextResolver;

    /**
     * @param UrlMatcherInterface|RequestMatcherInterface $matcher
     */
    public function __construct($matcher, RequestContextResolverInterface $contextResolver)
    {
        $this->matcher = $matcher;
        $this->contextResolver = $contextResolver;
    }

    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());
        }

        $event->getRequest()->attributes->add($parameters);

        $this->contextResolver->resolve($event->getRequest());

        $context = $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_CONTEXT_OBJECT);

        // ...
    }
}

You can also get the SalesChannelContext like this:

$request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  • Related