Laravel 5: Using Cache:: or DB:: within the Consol

2019-08-11 14:36发布

I'm trying to run an Artisan console command in Laravel 5 at varying, user-configured time intervals. I have built the console command and have a database (with Eloquent model) holding a "run frequency" configuration value.

Within the schedule() function of App\Console\Kernel.php I'd like to pull this value out of the database and run the command as and when needed based on this value.

I receive a Fatal error: Class 'DB' not found when using DB::table()... with or without use DB;, and the same happens if I try to use Cache::... functions too.

I'm assuming the IoC container isn't accessible from within the schedule() function of App\Console\Kernel.php file. Has anyone had similar and found an elegant workaround?

My simplified code is:

<?php namespace App\Console;

use Cache;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $settings = Cache::get('settings');
    }

and the error:

php artisan schedule:run
PHP Fatal error:  Class 'Cache' not found in /home/vagrant/projects/project/dir/api/app/Console/Kernel.php on line 26

any help would be greatfully appreciated

1条回答
姐就是有狂的资本
2楼-- · 2019-08-11 15:08

This has been fixed by Taylor in 5.0.21 (Git Commit) so anyone experiencing the same issue can run composer update to get the latest version of the framework which will allow you to use

Use DB;

Use Cache;

etc as usual

查看更多
登录 后发表回答