链接 PHP 中的方法并将第一个调用的方法作为最后一个执行,它是如何工作的?
Chaining methods in PHP and execute the first called method as last, how does it work?
我和 Laravel 一起工作了一段时间,从一开始我就想知道他们如何能够以随机顺序链接方法并且仍然将整个链作为一个操作执行。
例如在控制台内核中:
protected function schedule(Schedule $schedule)
{
$schedule->command('some-command')
->everyThirtyMinutes()
->before(function (Schedule $schedule) {
$schedule->command('some-other-command');
});
}
首先调用command
方法,但命令每三十分钟只会运行。该信息是在调用 command
方法之后出现的,但在执行它之前仍会进行处理。 before
方法也是如此。该方法是最后调用的,但 some-other-command
命令仍先执行。
我在互联网上搜索了答案,但找不到。希望你知道答案。
That method is called last, but the some-other-command command is still being executed first.
因为 before()
方法就是这样做的,所以在当前命令之前放置另一个命令(因此得名)。
正如 class 名称 Scheduler
所暗示的那样,它正在设置一些时间表,而不是按原样执行代码,所以问题是对代码的作用的误解。
这取决于您使用链接的上下文,在您的示例中,第一种方法是 command :
Add a new Artisan command event to the schedule.
并且它 return 是一个 Event,这个 Event 实例有很多方法可以在链接模式下调用,因为它们 return $this
表示它们 return 事件的当前实例,以便您可以调用 Event` class 提供的其他方法。
在你的例子中
Schedule the event to run every thirty minutes.
Return Value : $this
Register a callback to be called before the operation.
Return Value : $this
关于您必须先调用 command
以获取 Event
实例的顺序,对于其他两个方法,该顺序无效。
就像你告诉某人每 30 分钟去一次市场并在每次关门之前告诉他(或她)在你去市场之前关门并且每三十分钟去一次。
我和 Laravel 一起工作了一段时间,从一开始我就想知道他们如何能够以随机顺序链接方法并且仍然将整个链作为一个操作执行。
例如在控制台内核中:
protected function schedule(Schedule $schedule)
{
$schedule->command('some-command')
->everyThirtyMinutes()
->before(function (Schedule $schedule) {
$schedule->command('some-other-command');
});
}
首先调用command
方法,但命令每三十分钟只会运行。该信息是在调用 command
方法之后出现的,但在执行它之前仍会进行处理。 before
方法也是如此。该方法是最后调用的,但 some-other-command
命令仍先执行。
我在互联网上搜索了答案,但找不到。希望你知道答案。
That method is called last, but the some-other-command command is still being executed first.
因为 before()
方法就是这样做的,所以在当前命令之前放置另一个命令(因此得名)。
正如 class 名称 Scheduler
所暗示的那样,它正在设置一些时间表,而不是按原样执行代码,所以问题是对代码的作用的误解。
这取决于您使用链接的上下文,在您的示例中,第一种方法是 command :
Add a new Artisan command event to the schedule.
并且它 return 是一个 Event,这个 Event 实例有很多方法可以在链接模式下调用,因为它们 return $this
表示它们 return 事件的当前实例,以便您可以调用 Event` class 提供的其他方法。
在你的例子中
Schedule the event to run every thirty minutes.
Return Value : $this
Register a callback to be called before the operation.
Return Value : $this
关于您必须先调用 command
以获取 Event
实例的顺序,对于其他两个方法,该顺序无效。
就像你告诉某人每 30 分钟去一次市场并在每次关门之前告诉他(或她)在你去市场之前关门并且每三十分钟去一次。