zhiyong's avatar

Best place to store constants shared by multiple Controllers?

Hi,

The title pretty much says it. In Laravel, we can store all constants under Config, then use Config facade to access it. This is really convenient. But Config facade seems deprecated or may incur some performance costs. So what are the best way/practice store constants?

Please advise. Thanks in advance.

Zhiyong.

0 likes
8 replies
ahuggins's avatar

If you feel Config is costing you performance, you can try using the php artisan config:cache command. This will create a cache of your config, which means it's basically just loading an array (I believe) from a static file, which should be about as fast as possible. Also, you can use the Config facade or the config('app.something') helper function in order to access the value you want.

zhiyong's avatar

@ahuggins I believe in Lumen config just loads the value from .env file, equivalent to env('key'). I would prefer to store those shared constants in some file that is version controlled.

simondavies's avatar

i have mine in a constants fiel within the config folder, then just use the config('..')to load them etc

constants.php

return [
    'MY_CONST_VALUE' => 'value',
    ];

Called like the following:

    $whatsMyValue = config('constants.MY_CONST_VALUE);
zhiyong's avatar

@simondavies Did you enable facade or do something else? When I did exactly the same as you did, then

echo $whatsMyValue;

I get nothing.

simondavies's avatar

@zhiyong should not have to all config files get loaded in, post your actual code, to help, where you putting this etc

zhiyong's avatar

@simondavies I thought config() will automatically look for constants.php under /config folder. I guess I need to load this file manually in compose.

jimmck's avatar

I would recommend you load constants as php constants in the Lumen bootstrap. You don't have store them in arrays.

Bonsi's avatar
Bonsi
Best Answer
Level 20

I personally like to create a file called "constants.php" somewhere under the project tree then autoload it using composer. For example:

"autoload": {
    "files": [
        "src/App/constants.php"
    ]
}

Please or to participate in this conversation.