Search code examples
cakephpcommand-line-interfacecakephp-4.x

CakePHP 4 custom shell script on Command


Is there any way of running a shell command DIRECTLY on the Command Class for CAkePHP4? I would like something like this.

class SyncProjectsCoursesCommand extends Command
{
    public function execute(Arguments $args, ConsoleIo $io): int
    {

        // Custom MySQL shell command
        $this->run("mysql -u qstimuser --password=$DPASS --database=tims2 --host=10.10.9.60 --execute='...'");
      
       // Or customer .sh file on Linux bin
       $this->run("custom-shell-command.sh") 

        return static::CODE_SUCCESS;
    }
}

?>


Solution

  • Command::run() is used to run the current command, you don't call it yourself for any other purpose, it will get called when you run the command from the CLI.

    There are no specific methods to run external executables, but CakePHP is still just PHP, so you can use the native PHP commands. Long story short, use PHP's native methods, like exec(), system(), passthru(), etc... (and don't forget to escape input that you pass to the CLI!):

    $DPASS = escapeshellarg($DPASS);
    $result = exec("mysql -u qstimuser --password={$DPASS} --database=tims2 --host=10.10.9.60 --execute='...'");
    

    See also