dynamic theme switching for mobile

What is the best place to hook in dynamic theme switching on a per-request basis?

My use case is switching themes for mobile devices, on a per-user basis; I don’t want to be setting Yii:app()->theme=‘sometheme’.

I am storing a theme name in the session to identify the user’s theme preference, and I am looking for where the theme gets applied to the response. I think it would be some part of the request life cycle, but what is the best place?

FYI, I have a Controller that extends CController. My Controller is extended by all of my other Controller classes. I have tried to overwrite the following methods in Controller, but no luck:

public function beforeAction($action){

$userSelectedTheme = Yii::app()->session['themename'];


$this->layout = '//layout/'.$userSelectedTheme;


parent::beforeAction($action);

public function getLayoutFile($layoutName){

if (Yii::app()->session['themename']=='mobile'){


    	$layoutName = '//themes/mobile/'.$layoutName;


}


parent::getLayoutFile($layoutName);

}

[color="#006400"]/* Moved from Tips and Snippets to Yii 1.1 General Discussion */[/color]

My suggestion is to create new event-handler that will be triggered by onBeginRequest event.

For example:




<?php

    class BeginRequestBehavior extends CBehavior

    {

        public function attach($owner)

        {

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

        }


        public function switchThemes($event)

        {

           //Some logic that will determine which theme to use

            Yii::app()->theme = $determinedTheme;

        }

     }

?>



Also in your config files, you will need to add line(if you saved BeginRequestBehavior under components folder):




'behaviors' => array(

            'onBeginRequest' => array(

                'class' => 'application.components.BeginRequestBehavior'

            ),

        ),



@Ivica - thanks, that was good advice for a hook into the request life-cycle!

I do wonder about changing application-scope variables on a per-request basis.

So another part to this question is, what the best way to switch themes on a per-user basis without affecting application scope?