微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

有人知道如何检查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',FILE_APPEND | LOCK_EX);

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

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。