我想从 magento 观察者执行 shell 命令,但出现以下错误。
命令返回非零退出代码:
sudo php -dmemory_limit=5G bin/magento cache:disable 2>&1
我正在使用下面的代码。
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Shell;
use Magento\Framework\Shell\CommandRenderer;
class Productsaveafter implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$this->_shell = new Shell(new CommandRenderer());
$this->_shell->execute("sudo php -dmemory_limit=5G bin/magento cache:clean");
}
}
任何帮助/建议将非常适用
这里是运行 magento 的 shell 命令的帮助程序类。您可以实例化这个帮助器类,然后在观察者中调用execute()函数。
顺便说一句,你不应该使用
sudo
,因为我认为你运行 php/nginx/apache 的帐户不能使用sudo
。
<?php
namespace <Your full namespace>
use Magento\Framework\Shell;
use Symfony\Component\Process\PhpExecutableFinder;
class RunCleanCacheCommand
{
/**
* @var Shell
*/
private $shell;
/**
* @var PhpExecutableFinder
*/
private $phpExecutableFinder;
public function __construct(
Shell $shell,
PhpExecutableFinder $phpExecutableFinder
) {
$this->shell = $shell;
$this->phpExecutableFinder = $phpExecutableFinder;
}
public function execute()
{
$phpPath = $this->phpExecutableFinder->find() ?: 'php';
try {
$this->shell->execute($phpPath . ' %s cache:clean', [BP . '/bin/magento']);
} catch (\Exception $e) {
//Log error here
}
}
}