While Yii will perform a lot of module routing for free, we have to add our routes to our CUrlManager configuration in main.php at protected/config/ in order for our module to have any custom routing. While it’s easy to execute, this method does not keep our module and application configurations sufficiently separated. To get around this limitation in Yii, we need to modify the CMSUrlManager class that we created in the previous chapter in order to retrieve custom module routes that we define. This enables us to write routes as part of our module rather than as part of our application. The steps are as follows:

  1. Start by creating a new file, routes.php, in protected/modules/dashboard/config/, that contains the following. For this module, we’ll define a custom route for our save actions to be loaded from:
    <?php return array(
       '/dashboard/<controller:\w+>/save' => '/dashboard/<controller>/save',


    This example is purely to illustrate how to add custom routing to a module, since Yii does not support it natively.

  2. With our custom route defined, we’ll next update CMSUrlManager to automatically import these rules. Open CMSUrlManager.php at protected/components/, and add the following to the if block of the processRules() method:
    $this->rules = CMap::mergearray($this->addModuleRules(), $this->rules);
  3. We’ll finally define a addModuleRules() method that will search all of our installed modules for a routes.php file at config/ and register them with Yii:
    private function addModuleRules()
        // Load the routes from cache
        $moduleRoutes = array();
        $directories = glob(Yii::getPathOfAlias('application.modules') . '/*' , GLOB_ONLYDIR);
        foreach ($directories as $dir)
            $routePath = $dir .DS. 'config' .DS. 'routes.php';
            if (file_exists($routePath))
                $routes = require_once($routePath);
                foreach ($routes as $k=>$v)
                    $moduleRoutes[$k] = $v;
        return $moduleRoutes;