Laravel 5 Commands - Execute one by one

I have CustomCommand_1

and CustomCommand_2

.

How do I create a pipeline of commands and execute CustomCommand_2

immediately after execution CustomCommand_1

? (without calling a command inside another).

+3


source to share


3 answers


I couldn't find a way to do this, so I came up with a workaround (tested on laravel sync

).

First you have to create / edit a basic command:

namespace App\Commands;

use Illuminate\Foundation\Bus\DispatchesCommands;

abstract class Command {
    use DispatchesCommands;
    /**
     * @var Command[]
     */
    protected $commands = [];

    /**
     * @param Command|Command[] $command
     */
    public function addNextCommand($command) {
        if (is_array($command)) {
            foreach ($command as $item) {
                $this->commands[] = $item;
            }
        } else {
            $this->commands[] = $command;
        }
    }

    public function handlingCommandFinished() {
        if (!$this->commands)
            return;
        $command = array_shift($this->commands);
        $command->addNextCommand($this->commands);
        $this->dispatch($command);
    }
}

      

Each command should call $this->handlingCommandFinished();

when they complete execution.

With this you can link your commands:

$command = new FirstCommand();
$command->addNextCommand(new SecondCommand());
$command->addNextCommand(new ThirdCommand());
$this->dispatch($command);

      




Pipeline

Instead of being called handlingCommandFinished

in each command, you can use a command pipeline!

In App\Providers\BusServiceProvider::boot

add:

$dispatcher->pipeThrough([
    'App\Commands\Pipeline\ChainCommands'
]);

      

Add create App\Commands\Pipeline\ChainCommands

:

class ChainCommands {
    public function handle(Command $command, $next) {
        $result = $next($command);
        $command->handlingCommandFinished();
        return $result;
    }
}

      

0


source


You can use a callback to decide when something will or won't work using when () or skip ():

$schedule
    ->call('Mailer@BusinessDayMailer')
    ->weekdays()
    ->skip(function(TypeHintedDeciderClass $decider)
    {
        return $decider->isHoliday();
    }
);

      



Submitted by: Event Scheduling and Commands and Handlers

You can also read how to add commands to the queue here . See if this helps.

+1


source


What's stopping you from doing the following?

$this->dispatch(new CustomCommand_1);
$this->dispatch(new CustomCommand_2);
// And so on

      

0


source







All Articles