I need to inject the requestStack in an event subscriber but it looks like I'm doing something wrong (when the class gets constructed) but I'm not sure what it is.
First I'm subscribing to onLineItemAdded
then I want to set a new field in the payload but there is an error regarding the passing of RequestStack $requestStack. should be there any extra XML config that I need to add in order for this to work properly?
<?php declare(strict_types=1);
namespace Test\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
class TestCartSubscriber implements EventSubscriberInterface
{
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
BeforeLineItemAddedEvent::class => 'onLineItemAdded'
];
}
public function onLineItemAdded(BeforeLineItemAddedEvent $event): void
{
// $lineItem = $event->getLineItem();
$items = $this->requestStack->getCurrentRequest()->get('lineItems');
print_r($items);exit;
}
}
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="Test\Subscriber\TestCartSubscriber">
<tag name="kernel.event_subscriber"/>
</service>
</services>
</container>
CodePudding user response:
You have to inject the request stack in the XML:
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="Test\Subscriber\TestCartSubscriber">
<argument type="service" id="request_stack"/>
<tag name="kernel.event_subscriber"/>
</service>
</services>
</container>
See the Symfony documentation for more information on how the constructor injection works.