Laravel自定义帮助程序 - 未定义的索引SERVER_NAME


Laravel custom helper - undefined index SERVER_NAME

在Laravel 5.1中,我创建了一个自定义的帮助程序文件: custom.php我在composer.json中加载:

"autoload": {
    "files": [
        "app/Helpers/custom.php"
    ]
},

它包含此方法:

function website() {
    return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
}

它按预期工作,但每次我执行php artisan命令时,我都会收到一个调用堆栈和以下消息:

Notice: Undefined index: SERVER_NAME in /path/to/custom.php on line 4

为什么会这样?该方法从我的 Laravel 应用程序中运行时返回正确的值。

$_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 run 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']);
    }
}

希望这对你有帮助。

Artisan 在命令行上工作,因此没有SERVER_NAME。使用类似以下内容:

Request::server('SERVER_NAME', 'UNKNOWN')

而不是 $_SERVER[] 来提供默认值以避免错误。

也许是因为当您像往常一样运行此帮助程序时,SERVER_NAME其中包含一些内容,因为您从浏览器运行它。

当您运行 Artisan 命令时,没有任何服务器,这就是SERVER_NAME为空的原因。