Laravel 5-如何从Artisan Command运行Controller方法? [英] Laravel 5 - how to run a Controller method from an Artisan Command?

查看:567
本文介绍了Laravel 5-如何从Artisan Command运行Controller方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Controller中获取一些代码才能每十分钟运行一次.使用SchedulerCommands足够容易.但.我创建了一个Command,并在Laravel Scheduler中(在Kernel.php中)注册了它,现在我无法实例化Controller.我知道这是解决此问题的错误方法,但我只需要进行快速测试.请注意,您有没有办法做到这一点?谢谢.

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.

更新#1:

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()方法

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

这将返回一个FatalErrorException:

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

更新#2:

事实证明我在updateStats()方法中有一个错字,但是@ alexey-mezenin的回答却很吸引人!将Controller导入到Command中也足够了:

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

推荐答案

尝试在命令代码中使用use Full\Path\To\Your\Controller;并静态使用方法:

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

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

在您的命令代码中:

echo myClass::someStaticMethod();

这篇关于Laravel 5-如何从Artisan Command运行Controller方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆