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

陌路散爱 提交于 2019-12-30 10:16:09

问题


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?

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:

Call to undefined method 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

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/18607012/executing-a-route-controller-action-using-php-cli-and-detecting-a-cli-request

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