Shopware 6模块配置保存后统一执行后置处理方案问询
解决Shopware 6模块配置批量保存后的后置处理问题
方案1:用system_config.batch_written事件(推荐,适配Shopware 6.4+)
这个事件会在所有配置项批量写入完成后只触发一次,完美匹配需求。代码示例:
use Shopware\Core\System\SystemConfig\Event\SystemConfigBatchWrittenEvent; public static function getSubscribedEvents(): array { return [ SystemConfigBatchWrittenEvent::class => 'onBatchConfigSaved', ]; } public function onBatchConfigSaved(SystemConfigBatchWrittenEvent $event): void { // 筛选出当前模块的配置(替换成你的模块配置前缀) $moduleConfigs = array_filter($event->getKeys(), function($key) { return str_starts_with($key, 'YourPlugin.config.'); }); // 只有当当前模块的配置被修改时,才执行后置处理 if (!empty($moduleConfigs)) { $this->executePostProcessing(); } } private function executePostProcessing(): void { // 这里写你的后置处理逻辑,比如更新缓存、同步数据等 }
方案2:兼容全Shopware 6版本的通用方案
如果要适配从6.0到最新的所有版本,结合system_config.written和内核终止事件来实现,确保只执行一次处理:
1. 先做一个状态标记服务
用来记录是否需要执行后置处理:
// src/Service/ConfigSaveMarker.php namespace YourPlugin\Service; class ConfigSaveMarker { private bool $needsProcessing = false; public function mark(): void { $this->needsProcessing = true; } public function shouldProcess(): bool { return $this->needsProcessing; } public function reset(): void { $this->needsProcessing = false; } }
2. 注册这个服务
在你的模块services.yaml里加一行:
# src/Resources/config/services.yaml services: YourPlugin\Service\ConfigSaveMarker: public: true
3. 订阅事件并处理
use Shopware\Core\System\SystemConfig\Event\SystemConfigWrittenEvent; use Symfony\Component\HttpKernel\Event\TerminateEvent; use Symfony\Component\HttpKernel\KernelEvents; public static function getSubscribedEvents(): array { return [ SystemConfigWrittenEvent::class => 'onSingleConfigSaved', KernelEvents::TERMINATE => 'onRequestEnd', ]; } public function __construct( private readonly ConfigSaveMarker $marker ) {} public function onSingleConfigSaved(SystemConfigWrittenEvent $event): void { // 检查当前修改的配置是否属于你的模块 if (str_starts_with($event->getKey(), 'YourPlugin.config.')) { $this->marker->mark(); } } public function onRequestEnd(TerminateEvent $event): void { if (!$this->marker->shouldProcess()) { return; } // 执行后置处理 $this->executePostProcessing(); // 重置标记,防止后续请求误触发 $this->marker->reset(); } private function executePostProcessing(): void { // 你的后置处理逻辑写在这里 }
原理说明
- 每次单个配置项被保存时,只要是你模块的配置,就标记需要处理
- 请求结束时(
KernelEvents::TERMINATE)检查标记,执行一次处理后重置状态 - 不管是单个还是批量保存配置,最终只会执行一次后置处理,兼容所有Shopware 6版本
内容的提问来源于stack exchange,提问作者Miguel
相关产品推荐
相关产品推荐

