laravel 使用 PHP CLI 执行路由(控制器/操作)并检测 CLI 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18607012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:22:38  来源:igfitidea点击:

Executing a Route (Controller/Action) using PHP CLI and Detecting a CLI Request

laravellaravel-4command-line-interface

提问by sharmil

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 4 中有没有办法使用 PHP-CLI 运行我的控制器/动作?我有一个控制器/操作,如果请求来自 CLI,我想扩展它以执行替代操作,那么有没有办法将请求标识为 CLI 请求?

The Laravel documentation on this siteseems 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:

在Laravel文档此网站似乎表明,存在一种方法,支持:: CLI(),用于确定如果当前请求是经由工匠CLI但是当我在Laravel 4中使用的方法,它抛出一个错误:

Call to undefined method Illuminate\Http\Request::cli()

调用未定义的方法 Illuminate\Http\Request::cli()

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

基本上,我刚刚从 CakePHP 转移到 Laravel,并希望完成类似于本文中描述的事情(对于 CakePHP):Calling controller actions from cron and the command line

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?

我知道我可以使用 Laravel 4 Artisan 命令,但是我想使用的方法可行吗?如果是这样,如何?

回答by Javi Stolz

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'.

正如 Rob 已经说过的,要确定当前脚本是在控制台中运行App::runningInConsole()还是使用简单的普通 PHP php_sapi_name() == 'cli'

As for running controller@action from console, you could use curlor wgetto 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@action,您可以使用curlwget请求您的路线之一,但我认为正确的做法是使用自定义 artisan 命令。您的控制器是类,因此您可以实例化它们并在您的工匠命令中随意使用:

$controller = new SomeController;
$controller->someAction();

Watch this videofor an introduction to easily developing your own artisan commands.

观看此视频,了解如何轻松开发自己的工匠命令。