Laravel 5 “Class does not exist” when using the sc

2019-02-19 18:17发布

问题:

I'm trying to use the scheduler for the first time to call a method:

protected function schedule(Schedule $schedule)
    {   
        $schedule->call('MyClassName@myMethodName')
            ->everyMinute();
    }

The class I'm calling is defined in App/Http/Controller this way:

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Models\Reaction;
use View;
use Request;

class MyClassNameController extends Controller {

But each time the scheduler runs, it gaves:

  [ReflectionException]
  Class MyClassName does not exist

How could I fix this ?

回答1:

You should not call controller methods this way. Controller methods are meant for handling HTTP requests.

The content of myMethodName should be pulled out into a command. You can learn about creating commands here.

That aside, the reason you're getting the ReflectionException is because of the exact reason the exception states: MyClassName is not a valid class.

$schedule->call('App\Http\Controllers\MyClassNameController@myMethodName')

The above specifies the Fully Qualified Name of the class you are trying to refer to. You could alternatively import that class at the top of your file and use a join

use App\Http\Controllers\MyClassNameController;

// ...

$schedule->call(join('@', [ MyClassNameController::class, 'myMethodName ]))

But again, you should not be calling controller methods this way.