Best Practice For Multi-Roles Views


I plan to have multi-roles and what I plan to do is having multiple sub-views for each Item to reduce check in view code. For example I will have Author, Admin and Guests (aka normal users) and want to do something like

public function actionIndex()


	$view = null;


    	$view = $this->render('admin/index', ['username' => 'samdark']);

	else if(role_is_author)

    	$view = $this->render('author/index', ['username' => 'samdark']);


    	$view = $this->render('normal/index', ['username' => 'samdark']);


Is it acceptable way?

Is there a better way?

Am still getting used to Yii2 concept and if I miss something I will be happy to be corrected :)



It seems to look ok what you have. Based on the design, you may also try to create a generic method or a super Controller. Not sure if something like the following is possible in your design:

// Create a base app controller

class AppController extends \yii\web\Controller {

    private static $_roles = [

        0 => 'admin',

        1 => 'author',

        2 => 'normal'


    public function renderView($view, $params) {

        $role = Yii::$app->user->role; // or whatever

        return $this->render(self::$_roles[$role] . '/' . $view, $params);



// Your other controllers extend AppController

class YourController extends AppController {

    public function actionIndex() {

        return $this->renderView('index', ['username'=>'samdark']);



Yeah its possible,

thanks for the comment!