Search code examples
phpconfigurationyii2

Merge multiple configuration file in Yii


My Yii application consists of 4 modules. Each module has its own config file main.php listing configuration for only url manager.I have all other configurations inside /config/main.php of application directory. Is there a solution to mere each of the modules configuration into main configuration file ?


Solution

  • I am not sure if your using Yii 1 or 2. Your question says Yii but is tagged as yii2.

    If its Yii 1, then try this -

    You have 4 modules. They must be located at
    /protected/modules/MODULE_NAME1, /protected/modules/MODULE_NAME2, and the other two.

    Each module having its own main.php consists of array for UrlManager. Lets say you have a config folder in each MODULE_NAME folder and main.php in it.
    So the location becomes - /protected/modules/MODULE_NAME1/config/main.php.

    Now, in the index.php, you must be having a line of code as $config=dirname(__FILE__).'/protected/config/main.php';

    This is how the main.php(located at /protected/config/main.php) data is fetched.

    So if you want to add more config arrays, then just fetch each of them and merge with the primary one.

    Eg:

    $config = array_merge(
        require(dirname(__FILE__).'/protected/config/main.php'),
        require(dirname(__FILE__).'/protected/modules/MODULE_NAME1/config/main.php'),
        require(dirname(__FILE__).'/protected/modules/MODULE_NAME2/config/main.php'),
        require(dirname(__FILE__).'/protected/modules/MODULE_NAME3/config/main.php'),
        require(dirname(__FILE__).'/protected/modules/MODULE_NAME4/config/main.php'),
    );
    

    Make sure the arrays returned from the Module's main.php have the same structure for urlManager.