首页 > 解决方案 > Shopware 6:如何通过 SalesChannel 级别的 EventSubscriberInterface 检测任何类别添加/更新?

问题描述

有谁知道如何检查 Shopware 6 中是否正在添加/更新/删除特定类别?

我想Symfony\Component\EventDispatcher\EventSubscriberInterface通过订阅者使用还是必须实现任何其他东西?

更新:能够找到几个与实体相关的事件,但仍然无法区分(检测)类别是否正在添加或修改

插件/src/Resources/config/services.xml

<!-- ... -->
<service id="MyPlugin\MySubscriber">
    <tag name="kernel.event_subscriber"/>
</service>
<!-- ... -->

我的订阅者.php

<?php declare(strict_types=1);

namespace MyPlugin;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Category\CategoryEvents;
use Shopware\Core\Content\Category\Event\CategoryIndexerEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;

class MySubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            CategoryEvents::CATEGORY_INDEXER_EVENT => 'onCategoryIndex',
            CategoryEvents::CATEGORY_DELETED_EVENT => 'onCategoryDelete',
            CategoryEvents::CATEGORY_WRITTEN_EVENT => 'onCategoryWritten'
        ];
    }

    public function onCategoryWritten(EntityWrittenEvent $event): void
    {
        $ids = $event->getIds();    
        //how to check here whether category is adding or modified here or any other event.
        //EntityWrittenEvent in both actions(add/modify) this listener is triggering
        file_put_contents('/var/onCategoryWritten.text', print_r($ids, true), FILE_APPEND | LOCK_EX);
    
    }

    public function onCategoryDelete(EntityDeletedEvent $event): void
    {
        $ids = $event->getIds();
        file_put_contents('/var/onCategoryDelete.text', print_r($ids, true), FILE_APPEND | LOCK_EX);

    }
    
    public function onCategoryIndex(CategoryIndexerEvent $event): void
    {
        $ids = $event->getIds();
        file_put_contents('/var/onCategoryIndex.text', print_r($ids, true), FILE_APPEND | LOCK_EX);
    }
}

标签: shopware6

解决方案


您可以检查在写入结果中完成的操作,例如

foreach($event->getWriteResults() as $writeResult) {

    if ($writeResult->getOperation() === EntityWriteResult::OPERATION_INSERT) 
    {
        //entity created
    }
    if ($writeResult->getOperation() === EntityWriteResult::OPERATION_UPDATE) 
    {
        //entity updated/modified
    }
}

推荐阅读