0

In my Laravel application I saw these two lines in the Kernal.php


$schedule->job(new SendJoinerReminderEmails)->dailyAt('09:00');
$schedule->job(SendLeaverReminderEmails::class)->dailyAt('09:00');

Functionally are these the same, and is one more correct than the other?

Jesse Luke Orange
  • 1,949
  • 3
  • 29
  • 71

2 Answers2

3

new SendJoinerReminderEmails return class instance

SendLeaverReminderEmails::class path of class return string like App\Mails\SendLeaverReminderEmails

if you see job method

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));
    }

here if $job param is string then it will try get instance from the container or else it will take instance from the $job param

 $job = is_string($job) ? Container::getInstance()->make($job) : $job;

To check you can dd

dd(new SendJoinerReminderEmails)

or

dd(SendLeaverReminderEmails::class)

John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • So essentially there is a fundamental difference but in this case the framework doesn't care because it's flexible? – Jesse Luke Orange Jul 03 '21 at 11:52
  • 1
    @JesseOrange at the end job method use instance of class .you can read https://stackoverflow.com/questions/30770148/what-is-class-in-php this link – John Lobo Jul 03 '21 at 11:53
2

No, Class instance is not same as Class name.

  • new SomeClass() will return an instance or object on the class.
  • On the other hand SomeClass::class will return the fully qualified name of SomeClass

But in this case, both should work because the method job() accepts any of the class name or an instance.

If you pass the class name, it'll resolve the instance inside the method as follows-

$job = is_string($job) ? resolve($job) : $job;

See the full implementation of the job method below-

/**
 * 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));
}
Partharaj Deb
  • 864
  • 1
  • 8
  • 22