I’ve always used a Config class to store and retrieve configuration settings within my applications, but I’m not sure what it is but I’ve just never really liked this method of doing it for some reason.
class Config { /** * Development environment * @var boolean */ const FOO = 'bar; } echo Config::DEVELOPEMENT;
I’ve seen other frameworks use a config directory where each file returns an array, but they still use a Config::get()
or something similar to retrieve the value, so I wanted to separate each config file within a directory which simply returns an array like they did, but use a “helper” function so it can be used throughout the application without constantly referring to use *\Config
.
Here is a sample directory tree
root/ - config/ - app.php - database.php - mail.php - index.php
Here is an example of the app.php
configuration array
return [ 'foo' => 'bar', 'this' => [ 'should' => [ 'keep' => 'going' ] ] ];
The config
helper function
// Check if the function exists or not if (!function_exists('config')) { // Create the function function config($ setting) { // Split the dot notation into an array $ pieces = explode('.', $ setting); // Get the file name and remove it from the array $ file = array_shift($ pieces) . '.php'; // Set the path directory $ directory = 'config/'; // Check if the file exists or not if (file_exists($ directory . $ file)) { // Include the file $ config = include $ directory . $ file; // Cycle through the dot notation pieces array foreach ($ pieces as $ piece) { // Piece the dot notation together in the array $ config = $ config[$ piece]; } // Return the configuration setting value return $ config; } else { // Return file not found return false; } } }
And it would be called like this using dot notation for each index of the array, the first being the folder name
$ foo = config('app.foo'); $ name = config('app.this.should.keep'); echo $ foo . ' ' . $ name ; // Displays "bar going"
Everything works as expected but I have a couple of concerns, the first being any possible security flaws, I’m fairly positive it should be ok, but I’d rather make sure first!
Next is the include
line, if you were to have multiple config()
calls in a page, the configuration file is included multiple times, changing it to include_once
causes the script not to work and only the first call of config()
works correctly. So I’m worried about how bloating this function could be on a page with multiple calls!
Is there a better way of writing the foreach
loop appending each $ piece
to the $ config
array?
// Cycle through the dot notation pieces array foreach ($ pieces as $ piece) { // Piece the dot notation together in the array $ config = $ config[$ piece]; }
That’s about all I can really think of, but of course, the reason I’m asking is for any advice or better practices, slimmer more agile code to achieve the same results. Thanks in advanced!