我想在插件激活时为所有现有产品添加更多的产品价格。但激活过程在大约5秒后停止,因此产品价格仅加到60种产品中的24种。插件激活失败。
我不知道激活过程为什么会停止。我如何解决这个问题并将价格添加到所有产品中?
这是我的代码:
public function activate(ActivateContext $activateContext): void
{
// Get rule
$ruleRepository = $this->container->get('rule.repository');
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', 'XYZ'));
/** @var RuleEntity $rule */
$rule = $ruleRepository->search($criteria, $activateContext->getContext())->first();
$ruleId = $rule->getId();
// Add pricing rule to all products
$productRepository = $this->container->get('product.repository');
$products = $productRepository->search(new Criteria(), $activateContext->getContext());
$productPriceRepository = $this->container->get('product_price.repository');
/** @var ProductEntity $product */
foreach ($products as $product) {
$productPriceRepository->create([[
'id' => Uuid::randomHex(),
'productId' => $product->getId(),
'quantityStart' => 1,
'ruleId' => $ruleId,
'price' => [
[
'currencyId' => Defaults::CURRENCY,
'gross' => $product->getCurrencyPrice(Defaults::CURRENCY)->getGross(),
'net' => $product->getCurrencyPrice(Defaults::CURRENCY)->getNet(),
'linked' => true
]
],
]], $activateContext->getContext());
}
}
我认为代码需要大量内存,因为shopware 6 dal的内存非常昂贵。正如Michael T所说,你应该避免在插件的安装或激活过程中进行如此昂贵的操作。最佳做法是编写a(CLI命令,该命令需要在安装后手动执行(https://developer.shopware.com/docs/guides/plugins/plugins/plugin-fundamentals/add-custom-commands),或者b(如果您不希望手动操作,请在队列中创建由消息处理程序处理的条目(https://developer.shopware.com/docs/guides/plugins/plugins/framework/message-queue/add-message-handler)
插件的生命周期事件实际上不应该处理这样的大规模写操作。在不知道产品数量的情况下,这很容易成为内存耗尽引起的问题。为了验证您是否可以为您的标准设置合理的限制:
$criteria = new Criteria();
$criteria->setLimit(50);
除此之外,ProductEntity::getCurrencyPrice()
返回?Price
,因此在调用getGross
和getNet
之前,您需要检查它是否返回null
。我建议将此代码从生命周期处理程序中删除,并将其添加到自定义CLI命令中。