Laravel 5 - how to run a Controller method from an Artisan Command?

倖福魔咒の 提交于 2019-12-04 22:48:50

问题


I need some code from my Controller to run every ten minutes. Easy enough with Scheduler and Commands. But. I've created a Command, registered it with Laravel Scheduler (in Kernel.php) and now I am unable to instantiate the Controller. I know it's a wrong way to approach this problem, but I just needed a quick test. Is there a way, mind you a hacky way, to accomplish this? Thank you.

Update #1:

The Command:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\StatsController;


class UpdateProfiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update-profiles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Updates profiles in database.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        StatsController::updateStats('<theProfileName>');
    }
}

updateStats() method in StatsController.php

public static function updateStats($theProfileName) { 
   // the body
}

This returns a FatalErrorException:

[Symfony\Component\Debug\Exception\FatalErrorException] 
syntax error, unexpected 'if' (T_IF)

Update #2:

Turns out that I've had an typo in the updateStats() method, but the answer by @alexey-mezenin works like a charm! It is also enough to import the Controller into the Command:

use App\Http\Controllers\StatsController;

And then initialize it as you'd do normally:

public function handle() {
   $statControl        = new StatsController;
   $statControl->updateStats('<theProfileName>');
}

回答1:


Try to use use Full\Path\To\Your\Controller; in your command code and use method statically:

public static function someStaticMethod()
{
    return 'Hello';
}

In your command code:

echo myClass::someStaticMethod();


来源:https://stackoverflow.com/questions/36518225/laravel-5-how-to-run-a-controller-method-from-an-artisan-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!