使用PHP CLI执行路由(控制器/操作)并检测CLI请求 [英] Executing a Route (Controller/Action) using PHP CLI and Detecting a CLI Request
问题描述
Laravel 4中是否有一种使用PHP-CLI运行我的控制器/动作的方法?如果请求来自CLI,我想扩展其控制器/操作以执行其他操作,那么有没有办法将请求标识为CLI请求?
Is there a way in Laravel 4 to run my controller/action using PHP-CLI? I have a controller/action that I would like to extend to perform an alternative action if the request comes from the CLI, so is there a way to identify the request as a CLI request?
本网站上的Laravel文档似乎暗示用于确定当前请求是否通过Artisan CLI的方法Request :: cli(),但是当我在Laravel 4中使用该方法时,它会引发错误:
The Laravel documentation on this site seems to suggest that there is a method Request::cli() for determining if the current request is via the Artisan CLI but when I used the method in Laravel 4, it throws an error:
调用未定义的方法Illuminate \ Http \ Request :: cli()
Call to undefined method Illuminate\Http\Request::cli()
基本上,我刚刚从CakePHP迁移到Laravel,并希望完成类似于本文(针对CakePHP)中所述的内容:
Basically, I have just moved from CakePHP to Laravel and would like to accomplish something similar to as what's described in this article (for CakePHP) : Calling controller actions from cron and the command line
我了解我可以使用Laravel 4 Artisan Commands,但是我想使用的方法可行吗?如果可以,怎么办?
I understand that I can work with Laravel 4 Artisan Commands, but is the approach I would like to use possible? And if so, how?
推荐答案
如Rob所说,要确定当前脚本是否正在控制台中运行,请使用App::runningInConsole()
或简单的纯PHP php_sapi_name() == 'cli'
.
As Rob already said, to determine if the current script is being run in the console use App::runningInConsole()
or simple plain PHP php_sapi_name() == 'cli'
.
至于从控制台运行controller @ action,您可以使用curl
或wget
来请求一条路由,但是我认为这样做的正确方法是使用
As for running controller@action from console, you could use curl
or wget
to request one of your routes but I think the proper way of doing it would be to use a custom artisan command. Your controllers are classes so you can instantiate them and use as you please from within your artisan command:
$controller = new SomeController;
$controller->someAction();
观看此视频,以轻松开发自己的工匠命令.
Watch this video for an introduction to easily developing your own artisan commands.
这篇关于使用PHP CLI执行路由(控制器/操作)并检测CLI请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!