Add custom routes to a module in yii 2 framework

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',
    );

    Note

    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;

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

  • porcelanosa

    It`s not Yii2 , it`s Yii 1

Pin It on Pinterest

Shares