duannuan0074 2016-10-08 00:02
浏览 89

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

I need to use one parameter from global variable $_SERVER in my config file (app.php), so that I can access SERVER_NAME and define which static resource server to use.

$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,
];

Is there a better way to achieve this other than using $_SERVER directly in laravel-config file?

  • 写回答

1条回答 默认 最新

  • dongluanan7163 2018-01-11 16:04
    关注

    You may use the Request façade to access the $_SERVER super-global.

    echo Request::server('SERVER_NAME');
    

    As an opinion side note, I generally agree with @ArtisticPhoenix's comment about readability and distaste for framework wrappers around basic functionality. However, using the wrappers for super-globals makes it a lot simpler to unit test. Also, of little relevant importance, there are some popular style guides out there that will fail you for direct access of the super-globals.

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程