change layout depending on user role

Hey all,

What would be considered best practise for changing the layout of all controllers/actions depending on the role of the logged in user? (using rbac)

Should i extend CController (say CBaseController extends CController) and create a beforeAction in it, to check which role the user has?

for example:

check if the array Yii::app()->authManager->getAuthItems(2, Yii::app()->user->id)) contains a specific role and set the layout accordingly?

Or is there a more elegant way?

I have read posts where people create a whole module for each role but my role dependent layouts only differ in menustructure, so it doesn’t feel very dry…

Thx

The solution i created:

in UserIdentity i saved the role of the user in a session variable:




            // Store the role in the session:

            $arrayAuthRoleItems = Yii::app()->authManager->getAuthItems(2, $user->id);

            $arrayKeys = array_keys($arrayAuthRoleItems);

            $role = strtolower ($arrayKeys[0]);

            $this->setState('role', $role);



I created a MyBaseController, which i extend by all my controllers, in which i created a beforeAction:




    protected function beforeAction($action) {

        // set layout depending on user role.. see UserIdentity

        if(isset(Yii::app()->user->role)){

            Yii::app()->layout = Yii::app()->user->role;

        } else {

            Yii::app()->layout = 'guest';

        }

        return parent::beforeAction($action);

    }



If there is a more elegant way, let me know.

Grtz

Hello

did you find a better solution? I have almost the same case, and I used this way before, but I’m looking for a more elegant way.

to be exact, a have 2 main roles: say author and reader. each user with specific credentials can take each or both.

the site layout have to determined based on role, users that have both roles, have a link to change the active role (hence change the layout)

Take a look at this wiki.

There is explained how to maintain the language, but you can do the same with the theme. Read only the part relative to the application behavior.

Hello,

why dont you simply create 2 modules that will contain each role,

which will have a very good layout and theme for each role.

you only need to find out the role in ur UserIdentity class then redirect the user to the appropriate module

this makes ur project more simple and easy to maintain.

in each module u can used the


 Yii::app()->theme ="author" 

to have different layouts /themes

hope this makes sense ::)

@zaccaria: i like the behaviour way you introduced, i’m going to use behaviours more and more :)

@binkabir: creating two modules is good idea, but in my case, the logic that control roles are so similar. i think i can handle them inside one module. for changing layouts, i created layouts for each role, and decide what to use based on data that i stored in session (via userIdentity).

thank you all