Yii Module Specific URL Rules

Sometimes ,We may have a set of URL Re-Writing Rules specifically for our modules..To achieve this follow the below Steps.

Step1:Add the below code into config/main.php

 

'onBeginRequest'=>function($event){
                    $route=Yii::app()->getRequest()->getPathInfo();
                    $module=substr($route,0,strpos($route,'/'));
                    if(Yii::app()->hasModule($module))
                    {
                      $module=Yii::app()->getModule($module);
                      if(isset($module->urlRules))
                      {
                        $urlManager=Yii::app()->getUrlManager();
                        $urlManager->addRules($module->urlRules);
                      }
                    }
                    return true;
                      },

Step2:Add a public varaible “$urlRules” inside your module file(eg:ApiModule.php).

eg:

 
public $urlRules=array(
                      'api/<controller:\w+>/<id:\d+>'=>'api/<controller>/view',
              'api/<controller:\w+>/<action:\w+>/<id:\d+>'=>'api/<controller>/<action>',
              'api/<controller:\w+>/<action:\w+>'=>'api/<controller>/<action>',
       );

Thats it. you are done..

happy coding

Nintriva

Leave a Reply

Your email address will not be published. Required fields are marked *