2014-09-02 85 views
1

在Laravel 4.2中,我使用App :: detectEnvironment根据机器名称更改数据库。我现在也需要根据环境变量改变环境。我试图结合,但目前它不工作,我不知道如何结合这两种技术。Laravel detectEnvironment - 如何结合机器名称和服务器变量?

使用机器名称:

$env = $app->detectEnvironment(array(

      'local' => array('.local', 'homestead'), 
      'staging' => array('ip-staging'), 
      'production' => array('ip-production') 
    ) 
); 

使用服务器环境变量:

$env = $app->detectEnvironment(function() 
{ 
    // Default to local if LARAVEL_ENV is not set 
    return getenv('LARAVEL_ENV') ?: 'local'; 
} 

非工作相结合的代码如下所示:

$env = $app->detectEnvironment(function() 
{ 
    // Default to machine name if LARAVEL_ENV is not set 
    return getenv('LARAVEL_ENV') ?: array(

     'local' => array('.local', 'homestead'), 
     'staging' => array('ip-staging'), 
     'production' => array('ip-production') 
    ); 

}); 
+0

您是否尝试过使用您的超级全局变量呢? 'return isset($ _ ENV ['LARAVEL_ENV'])? $ _ENV ['LARAVEL_ENV']:array(...);' - 可以用$ _SERVER替代 – JofryHS 2014-09-02 09:40:11

回答

2

找到了答案 - 感谢@ Marwelln的提示。

$env变量需要来自detectEnvironment函数才能被Laravel识别。

if (getenv('LARAVEL_ENV')) 
{ 
    $env = $app->detectEnvironment(function() 
    { 
      return getenv('LARAVEL_ENV'); 
    }); 
} 
else 
{ 
    $env = $app->detectEnvironment(array(
      // local development environments are set with machine host names 
      // developers find this out by typing 'hostname' at command line 

      'local' => array('*.local', 'homestead'), 
      'staging' => array('ip-staging'), 
      'production' => array('ip-production') 
    )); 
} 
1

这应该这样做。它设置为getenv('LARAVEL_ENV')中设置的环境,否则它使用默认的$app->detectEnvironment方法。

$env = getenv('LARAVEL_ENV') ?: $app->detectEnvironment(array(
    'local' => array('.local', 'homestead'), 
    'staging' => array('ip-staging'), 
    'production' => array('ip-production') 
));