Shopware 6:如何通过 SalesChannel 级别的 EventSubscriberInterface 检测任何类别添加/更新?

Posted

技术标签:

【中文标题】Shopware 6:如何通过 SalesChannel 级别的 EventSubscriberInterface 检测任何类别添加/更新?【英文标题】:Shopware 6 : how to detect any category add/update through EventSubscriberInterface on SalesChannel level? 【发布时间】:2021-01-11 22:02:38 【问题描述】:

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

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

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

plugin/src/Resources/config/services.xml

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

MySubscriber.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);
    

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

以上是关于Shopware 6:如何通过 SalesChannel 级别的 EventSubscriberInterface 检测任何类别添加/更新?的主要内容,如果未能解决你的问题,请参考以下文章

如何将自定义订单状态添加到 shopware 6

如何在 Shopware 6 中为订单添加自定义字段?

Shopware 6 : 如何使用 Shopware\Core\Content\Category\Event 中的 `CategoryIndexerEvent`

无法通过 Shopware 6 中的 XmlHttpRequest 请求 PageController

通过 ID 获取 Shopware 6 实体的推荐方法是啥?

如何扩展 Shopware 6 控制器操作