Laravel 5 Commands - Execute one by one
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;
}
}
source to share
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.
source to share