在Laravel 5中访问PHP超全局变量的最佳方式.X配置文件


Best way to access PHP super-global variables in Laravel 5.x config file

我需要在我的配置文件(app.php)中使用全局变量$_SERVER的一个参数,以便我可以访问SERVER_NAME并定义要使用的静态资源服务器。

$staticUrlMap['local.example.com'] = 'localstatic.example.com';
$staticUrlMap['dev.example.com'] = 'devstatic.example.com';
$staticUrlMap['stage.example.com'] = 'stagestatic.example.com';
$staticUrlMap['preprod.example.com'] = 'preprodstatic.example.com';
$staticUrlMap['my.example.com'] = 'static.example.com';
$staticUrl = '';
if(!empty($_SERVER['SERVER_NAME']))
{
    $staticUrl = $staticUrlMap[$_SERVER['SERVER_NAME']];
}
return [
    'static_url' => $staticUrl,
];

是否有更好的方法来实现这一点,而不是使用$_SERVER直接在larvel -config文件?

您可以使用Request参数来访问$_SERVER超全局变量。

echo Request::server('SERVER_NAME');

作为一个观点的边注,我基本上同意@ artiticphoenix关于可读性和对基本功能框架包装的厌恶的评论。但是,使用超全局变量的包装器可以使单元测试简单得多。此外,有一些流行的风格指南并不重要,它们无法让您直接访问超全局变量。