Laravel 5 - how to run a Controller method from an Artisan Command?(Laravel 5 - 如何从 Artisan 命令运行控制器方法?)
问题描述
我需要我的控制器中的一些代码每十分钟运行一次.使用 Scheduler
和 Commands
就足够简单了.但.我创建了一个 Command
,用 Laravel Scheduler
(在 Kernel.php
中)注册它,现在我无法实例化 控制器
.我知道这是解决此问题的错误方法,但我只需要进行快速测试.有没有办法,请注意一个hacky的方式,来完成这个?谢谢.
更新 #1:
命令
:
StatsController.php
updateStats()
方法
这将返回一个FatalErrorException
:
更新#2:
结果是我在 updateStats()
方法中有一个错字,但@alexey-mezenin 的回答很有魅力!把Controller
导入Command
也够了:
然后像往常一样初始化它:
尝试在命令代码中使用 use FullPathToYourController;
并静态使用方法:
在您的命令代码中:
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
:
updateStats()
method in StatsController.php
This returns a FatalErrorException
:
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
:
And then initialize it as you'd do normally:
Try to use use FullPathToYourController;
in your command code and use method statically:
In your command code:
这篇关于Laravel 5 - 如何从 Artisan 命令运行控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!