Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 968
deej Avatar asked Oct 08 '16 00:10

deej


People also ask

Which PHP super global variables are used to retrieve information from forms?

The $_REQUEST variable is a PHP superglobal that is used to collect data after submitting a form. It contains the contents of $_GET , $_POST and even $_COOKIE by default. Data from various fields can be collected by PHP using the $_REQUEST variable.

How get data from config file in Laravel?

use Config; $variable= Config::get('file1. EMP_DOC_PATH'); By this way you can get the variables value from config.

What is $_ global in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.


1 Answers

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.

like image 85
Jeff Puckett Avatar answered Sep 28 '22 22:09

Jeff Puckett