Laravel 自定义助手 - 未定义索引 SERVER_NAME
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35837248/
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
Laravel custom helper - undefined index SERVER_NAME
提问by Obay
In Laravel 5.1, I created a custom helper file: custom.php
which I load in composer.json
:
在 Laravel 5.1 中,我创建了一个自定义帮助文件:custom.php
我加载了它composer.json
:
"autoload": {
"files": [
"app/Helpers/custom.php"
]
},
and it contains this method:
它包含这个方法:
function website() {
return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
}
It works as expected, but every time I do php artisan
commands, I get a call stack and this message:
它按预期工作,但每次执行php artisan
命令时,我都会收到一个调用堆栈和此消息:
Notice: Undefined index: SERVER_NAME in /path/to/custom.php on line 4
Why is this so? The method returns the correct value when run from within my Laravel app.
为什么会这样?从我的 Laravel 应用程序中运行时,该方法返回正确的值。
回答by oseintow
$_SERVER['SERVER_Name'] global variable is only accessible when running your application through a browser. It will through an error when you run your application through php-cli/through the terminal. Change your code to
$_SERVER['SERVER_Name'] 全局变量只能在通过浏览器运行应用程序时访问。当您通过 php-cli/通过终端运行应用程序时,它会出错。将您的代码更改为
function website() {
if(php_sapi_name() === 'cli' OR defined('STDIN')){
// This section of the code runs when your application is being runned from the terminal
return "Some default server name or you can use your environment to set your server name"
}else{
// This section of the code run when your app is being run from the browser
return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
}
}
Hope this helps you.
希望这对你有帮助。
回答by markdwhite
Artisan works on the command line, so there is no SERVER_NAME. Use something like:
Artisan 在命令行上工作,因此没有 SERVER_NAME。使用类似的东西:
Request::server('SERVER_NAME', 'UNKNOWN')
instead of $_SERVER[] to provide a default to avoid the error.
而不是 $_SERVER[] 提供默认值以避免错误。
回答by Alexey Mezenin
Maybe it's because when you run this helper as usually, SERVER_NAME has something in it, because you run it from browser.
也许是因为当你像往常一样运行这个帮助程序时,SERVER_NAME 中有一些东西,因为你从浏览器运行它。
When you run Artisan command, there is not any server, that's why SERVER_NAME is empty.
当您运行 Artisan 命令时,没有任何服务器,这就是 SERVER_NAME 为空的原因。