Is there any solution to add routes from module configuration?
Example. We have main config where we describe
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => require(FILE_PATH_CONFIG_ENV . '_routes.php') // return array
],
]
in each module we load custom config file with private parameters
public function loadConfig($sFileName = 'main', $sFolderName = 'config')
{
Yii::configure($this, require($this->getBasePath() . DS . $sFolderName . DS . $sFileName . '.php'));
return $this;
}
Config file
return [
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
'rules' => [
'/admin' => '/admin/index/index',
]
]
]
];
And now I need somehow merge current config (main for web application) with config loaded from module. In end I want describe in module config routes only for this module and use them for pretty urls (user friendly url). How can I do this one? This examples not working when I create url /admin/index/index
, it shows me /admin/index/index
but I want /admin
as mentioned in module rules.
Separating url rules for modules is mentioned in official documentation here.
And I think this is more optimum approach unlike merging and declaring all rules in one config file.
The rules are parsed in order they are declared (this is mentioned here), so with the separation you can skip other modules urls. In case of large amount of rules it can give perfomance boost.
So I did this way (this is full answer for a question).
Create Bootstrap class special for module.
Create route file in module folder (/modules/XXX/config/_routes.php)
Add boostrap to main config file
That's it. We can define routes only in module 'route' config.
PS: I don't like detection
if (is_array($aModule) && strpos($aModule['class'], 'app\modules') === 0)
(I mean NOT 'debug', 'log', 'gii' or other native Yii2 modules) maybe someone can suggest better solution?And this will be more clean and reliable. I have found this on Yii2's github repo here.
and just configure your main.php config file's bootstrap section as