检测是否从Laravel 5中的命令行运行 [英] Detect if running from the command line in Laravel 5

查看:390
本文介绍了检测是否从Laravel 5中的命令行运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,如果通过Artisan从命令行运行应用程序(迁移,种子,route:list),我们需要修改应用程序流.

I have a use case where we need to modify application flow if the application is being run from the command line via Artisan (migrations, seeds, route:list).

在Laravel 4中,可以这样操作:

In Laravel 4 this could be done like this:

App::runningInConsole()

Laravel 5中是否有等效功能?

Is there an equivalent in Laravel 5?

在这种情况下,不建议使用环境(.env)变量,因为这些命令有时需要在生产环境上运行(指向生产资源),并且我宁愿避免诉诸于重复(.env.commandline)文件.

Using the Environment (.env) variables isn't preferred in this case as these commands occasionally need to be run on production (pointing to production resources) and I'd prefer to avoid resorting to duplicate (.env.commandline) files.

推荐答案

您可以使用PHP函数php_sapi_name(

You can use the PHP function php_sapi_name (http://php.net/manual/en/function.php-sapi-name.php), to found out if the script was launched from a command or not.

在您的情况下,您应该检查类似

In your case, you should check something like

if (strpos(php_sapi_name(), 'cli') !== false) {
    // Run from command
}

尽管如此,您可能必须检查文档以找到要检查的正确值. (有时可能会有所不同,但从根本上说,应该与通过命令启动的脚本的输出始终有所不同)

You may have to check the doc to find the proper value to check in each case though. (It may differ sometimes, but basically there should always be a different output from a script launched through a command)

这篇关于检测是否从Laravel 5中的命令行运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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