Search code examples
phplaravellaravel-4configsetting

How can i make laravel4 Config::get work like that way?


im laravel beginner i found a laravel 4 script using files in config directory to define site sitting in this way :

the configuration for the site is found in: directory ( config/site )

example :app/config/site/video.php

return [
    'max-size-upload-video' => [
        'type' => 'integer',
        'title' => 'Set Maximum Size Upload Video',
        'description' => 'Set the maximum size upload of videos',
        'value' => '10000000',
    ],
];

in the controller

Config::get('max-size-upload-video') is used to get the value and this is not the normal behavior of Config::get ..

my question is how i can make something like this? how i can make Config::get('the-property-title') get the value for me with out write the full path like normal way of using Config::get


Solution

  • Config files are loaded during application bootstrap process by Illuminate\Foundation\Bootstrap\LoadConfiguration class. If you want to change the way config files are loaded you'll need to implement your own loader by extending the existing one. Be careful to only change the way your own config files are loaded - do not change the way Laravel config files are loaded.

    Example loader:

    class CustomLoadConfiguration extends LoadConfiguration
    {
        protected function loadConfigurationFiles(Application $app, RepositoryContract $config)
        {
            foreach ($this->getConfigurationFiles($app) as $key => $path) {
                if ($key === 'video') {
                    $values = require $path;
                    if (is_array($values)) {
                        foreach ($values as $k => $value) {
                            $config->set($k, $value);
                        }
                    } else $config->set($key, $values);
                } else {
                    $config->set($key, require $path);
                }
            }
        }
    }
    

    Once you have your own loader add the following in your App\Http\Kernel class:

    protected function bootstrappers()
    {
        $bootstrappers = parent::bootstrappers();
        if (($key = array_search($bootstrappers, 'Illuminate\Foundation\Bootstrap\LoadConfiguration')) !== FALSE) {
            $bootstrappers[$key] = 'Your\Namespace\CustomLoadConfiguration';
        }
    
        return $bootstrappers;
    }
    

    WARNING: Before you do that, ask yourself if you really need this. Config files are namespaced in order to avoid conflicts - if you disable namespacing there is a risk of duplicated keys being loaded to config form different files and one of them overwriting the other.