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

dee*_*eej 6 php config laravel laravel-5

我需要$_SERVER在配置文件(app.php)中使用全局变量中的一个参数,以便我可以访问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,
];
Run Code Online (Sandbox Code Playgroud)

$_SERVER除了直接在 laravel-config 文件中使用之外,还有更好的方法来实现此目的吗?

Jef*_*ett 6

您可以使用Requestfa\xc3\xa7ade 来访问$_SERVER超级全局。

\n\n
echo Request::server('SERVER_NAME');\n
Run Code Online (Sandbox Code Playgroud)\n\n

作为意见旁注,我总体上同意 @ArtisticPhoenix 关于可读性和围绕基本功能的框架包装器的厌恶的评论。然而,使用超级全局的包装器使得单元测试变得更加简单。此外,不太重要的是,有一些流行的风格指南会让您无法直接访问超级全局变量。

\n