0

我创建了一个最低限度的 Shopware 6 插件来在加载产品时显示产品 ID。它工作得很好。下面是我的代码。

   PATH: src/Resources/config/services.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="TestPlugin\Listener\ProductLoadedListener" >
            <tag  name="kernel.event_listener" event="product.loaded" />
        </service>

    </services>
</container>

下面是 ProductLoadedListener.php 代码

PATH: src/Listener/ProductLoadedListener.php

<?php declare(strict_types=1);

namespace TestPlugin\Listener;

use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;

class ProductLoadedListener{
    


    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent){
        
        print_r($entityLoadedEvent->getIds());
    

    }

}

上面的代码完成了它被创建的工作。所以我更新了 ProductLoadedListener.php 代码

<?php declare(strict_types=1);

namespace TestPlugin\Listener;


use Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price;

class ProductLoadedListener{
    


    public function onProductLoaded(Price $price){
        
        print_r($price->getNet());
    

    }

}

我出错了

Argument 1 passed to TestPlugin\Listener\ProductLoadedListener::onProductLoaded() must be an instance of Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price, instance of Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent given, called in /var/www/html/vendor/symfony/event-dispatcher/EventDispatcher.php on line 270

所以我问为什么我得到上述错误,我期待它与净价相呼应?

4

1 回答 1

2

Shopware 将在onProductLoaded函数中注入一个EntityLoadedEvent对象,而不是一个Price对象。这就是 PHP 抛出此错误的原因。

如果要获取已加载产品的价格,则应从 获取产品,$entityLoadedEvent然后获取价格:

class ProductLoadedListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ProductEvents::PRODUCT_LOADED_EVENT => 'onProductLoaded'
        ];
    }

    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent)
    { 
        /** @var ProductCollection $loadedProducts */
        $loadedProducts = $event->getEntities();
        $firstProduct = $loadedProducts->first();
        $productNetPrice = $firstProduct->getPrice()->first()->getNet();
        dd($productNetPrice);
    }
}
于 2022-02-11T13:50:22.700 回答