在我的 Laravel 应用程序中,我在 Kernal.php 中看到了这两行
$schedule->job(new SendJoinerReminderEmails)->dailyAt('09:00');
$schedule->job(SendLeaverReminderEmails::class)->dailyAt('09:00');
这些功能在功能上是否相同,是否比另一个更正确?
new SendJoinerReminderEmails返回类实例
SendLeaverReminderEmails::class类返回路径string如App\Mails\SendLeaverReminderEmails
如果你看到job方法
public function job($job, $queue = null, $connection = null)
{
return $this->call(function () use ($job, $queue, $connection) {
$job = is_string($job) ? Container::getInstance()->make($job) : $job;
if ($job instanceof ShouldQueue) {
$this->dispatchToQueue($job, $queue ?? $job->queue, $connection ?? $job->connection);
} else {
$this->dispatchNow($job);
}
})->name(is_string($job) ? $job : get_class($job));
}
这里 if $job paramis stringthen 它将尝试从 the 获取实例,container 否则它将从$job param
$job = is_string($job) ? Container::getInstance()->make($job) : $job;
要检查你可以dd
dd(new SendJoinerReminderEmails)
或者
dd(SendLeaverReminderEmails::class)
不,Class instance与Class name不同。
new SomeClass()将返回类上的实例或对象。SomeClass::class将返回 SomeClass 的完全限定名但在这种情况下,两者都应该工作,因为该方法job()接受任何class name或instance。
如果您传递类名,它将解析方法内的实例,如下所示 -
$job = is_string($job) ? resolve($job) : $job;
job请参阅下面方法的完整实现 -
/**
* Add a new job callback event to the schedule.
*
* @param object|string $job
* @param string|null $queue
* @param string|null $connection
* @return \Illuminate\Console\Scheduling\CallbackEvent
*/
public function job($job, $queue = null, $connection = null)
{
return $this->call(function () use ($job, $queue, $connection) {
$job = is_string($job) ? resolve($job) : $job;
if ($job instanceof ShouldQueue) {
dispatch($job)
->onConnection($connection ?? $job->connection)
->onQueue($queue ?? $job->queue);
} else {
dispatch_now($job);
}
})->name(is_string($job) ? $job : get_class($job));
}