Dynamic default controller

For my app, I needed a dynamic default controller, because the app must display totally different content depending on which URL is being accessed.

Since you cannot assign dynamic values in the config/main.php (Yii has not loaded by that point), I used the following technique to do the job:




class SiteRouter

{

  public static function routeRequest($event)

  {

    $sender = &$event->sender;

    $defaultThemes = param('defaultThemes');

    $uri = empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST'];

    if($uri == param('adminUri')) {

      $sender->defaultController = 'admin';

      $sender->theme = $defaultThemes['admin'];

      return;

    } else {

      $site = Site::model()->findByAttributes(compact('uri'));

      if(!empty($site)) {

        $sender->defaultController = 'site';

        $sender->theme = empty($site->theme) ? $defaultThemes['site'] : $site->theme;

        return;

      }


      throw new CHttpException(404, 'Unable to find a site hosted here with that hostname');

    }

  }

}



Then in protected/config/main.php on the top-level of the config array:




...

  'onBeginRequest' => array('SiteRouter', 'routeRequest'),

  'params' => array(

    'defaultThemes' => array(

      'admin' => 'defaultAdminTheme',

      'site' => 'defaultSiteTheme',

    ),

  )

...



If there’s an easier way of doing this, please let me know.

BTW, this uses the shortcuts defined elsewhere on the site, such as param("…") for Yii:app()->params->{"…"}

This looks like a good solution too me. I did something like that in the index.php entry-script (for i18n-subdomaining). Your way seems way better.

Very nice!

Hi where I must write class SiteRouter?

create a file named "SiteRouter.php" in your application root components folder

It’s not clear why you need this functionality but this is one approach that I have used.

See Wiki Article

@datashaman I just looked a little closer at your post and I think the wiki example is very limited by comparison.

doodle