I want to run magento cli commands in magento 2.4.1 through button or action

有帮助吗?

解决方案

Given the fact that is an extremely insecure practice, you can.

The fast way would be to pass directly through the Shell object:

use Magento\Framework\Shell;
use Magento\Framework\Shell\CommandRenderer;

// put in your constructor
public function __construct() {
    $this->shell = new Shell(new CommandRenderer());
}

// put in your action execute method
public function execute() {
    $command = 'php bin/magento setup:upgrade';
    $this->shell->execute($command);
}

A cleaner way would be to find the command implementation in the source code and execute it in your action/button. The CLI commands are classes which extend the Symfony\Component\Console\Command\Command class. Once called, such class performs the code inside the execute() method.

Thus, you can use:

// put in your constructor
public function __construct(
    <Vendor>\<Module>\<PathToCommandClass> $command
) {
    $this->command = $command;
}

// in your action
public function execute() {
    $command->execute();
}

where $command is passed in the action constructor as a dependency.

许可以下: CC-BY-SA归因
scroll top