Magent2:shell 从观察者处执行命令

问题描述 投票:0回答:1

我想从 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");
    }
}

任何帮助/建议将非常适用

php magento magento2 magento2.4
1个回答
0
投票

这里是运行 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
        }        
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.