Magent2: shell execute command from observer

44 views Asked by At

I want to execute shell command from magento observer but getting below error.

Command returned non-zero exit code: sudo php -dmemory_limit=5G bin/magento cache:disable 2>&1

I am using below code.

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

Any help/suggestion will be much appricated

1

There are 1 answers

0
ndlinh On

Here is helper class to run magento's shell command. You can instance this helper class then call execute() function in Observer.

Btw, you should not use sudo because I don't think your account which running php/nginx/apache can use 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
        }        
    }
}