Dynamic URL manager routes

Extend the URL manager like so:




class MyUrlManager extends CUrlManager

{

  private function getRules()

  {

    if(somecondition) {

      $rules = array(

        ...

      );

    } else {

      $rules = array(

        ...

      );

    }


    return $rules;

  }


  protected function processRules()

  {

    $this->rules = $this->getRules();

    return parent::processRules();

  }

}



Use your new URL manager in config/main.php:




...

'urlManager' => array(

  'class' => 'MyUrlManager',

)

...



In my app I have different rules for different virtual hosts. The context decides how the URLs appear to the user.

You can’t specify dynamic rules directly in the config file, because Yii has not loaded by that point. This gives you the ability to make decisions on routing with the full framework at your disposal and before any rules have been evaluated.

Hi,

I’m a freshly new member and Yii user. I’m very interested by your post, as I’m looking for a system to provide international urls… Like for instance :

http://www.domain.com/topic would call the Topic controller for the ‘en’ language, and

http://www.domain.fr/sujet would call the Topic controller for the ‘fr’ language, and so on.

I handled the domain language recognition in the entry script, before Yii is even loaded… That’s maybe not the best way, but it also redirects aliases to default url, adds www if necessary (i.e. there’s not a subdomain in the request), etc. So I think it’s faster if it’s done before Yii is called and starts to work.

Back to the topic, would your method work for what I’m looking for? I’d like to test it but I’m really a newbie with Yii, and I don’t even know where to put your class file :D

Thanks for your help :)

edit : just found http://www.yiiframework.com/doc/cookbook/55/ which looks pretty interesting for me, hehe…

Nice solution, but maybe it’s possible to do something alike via behavior and event model?

I have found such solution:

config/main.php




...

	'behaviors' => array(

		'onbeginRequest' => array(

			'class' => 'application.components.StartupBehavior',

		),

	),

...



components/StartupBehavior.php




class StartupBehavior extends CBehavior

{

	public function attach($owner)

	{

		// set the event callback

		$owner->attachEventHandler('onBeginRequest', array($this, 'beginRequest'));

	}


	/**

	 * This method is attached to the 'onBeginRequest' event above.

	 **/

	public function beginRequest(CEvent $event)

	{

		$urlManager = Yii::app()->getUrlManager();

		if(somecondition) {

			$rules = array(

			 ...

			);

		} else {

			$rules = array(

			 ...

			);

		}

		$urlManager->rules = $rules;

		$urlManager->init();

	}

}



Pascool,

Your comment:




 "but it also redirects aliases to default url, adds www if necessary (i.e. there's not a subdomain in the request)"



How did you handle this? I was wanting to do this but really didn’t know where to start?