Shopware:在事件订阅者中注入 'requestStack'

Shopware: Injecting 'requestStack' in an event subscriber

我需要在事件订阅者中注入 requestStack 但看起来我做错了什么(当 class 被构建时)但我不确定它是什么。

首先,我订阅了 onLineItemAdded,然后我想在有效负载中设置一个新字段,但是在传递 RequestStack $requestStack 时出现错误。我应该添加任何额外的 XML 配置才能使其正常工作吗?

<?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>

您必须在 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>

有关构造函数注入如何工作的更多信息,请参见the Symfony documentation