Search code examples
phplaravelmethod-chaining

Chaining methods in PHP and execute the first called method as last, how does it work?


I'm working with Laravel for a little while now and since the start I have been wondering how they are able to chain methods in a random order and still execute the whole chain as one operation.

For example, in the console kernel:

protected function schedule(Schedule $schedule)
{
    $schedule->command('some-command')
        ->everyThirtyMinutes()
        ->before(function (Schedule $schedule) {
            $schedule->command('some-other-command');
        });
}

The command method is called first, but the command will only run every thirty minutes. That information came after calling the command method, but is still processed before executing it. The same goes for the before method. That method is called last, but the some-other-command command is still being executed first.

I've searched the internet for the answer, but I couldn't find one. I hope you know the answer.


Solution

  • That method is called last, but the some-other-command command is still being executed first.

    Because that is what the before() method does, placing another command before (hence the name) the current command. And as the class name Scheduler implies, it's setting up some schedule, not executing the code as is, so the question is rather a misunderstanding of what the code does.