Yii framework - how to specify the same access rules for all controllers of the module?

StackOverflow https://stackoverflow.com/questions/1612472

  •  06-07-2019
  •  | 
  •  

Question

I created module for admin specific operations. I don't want to write the same access rules for every controller, it's not pretty coding style.

Was it helpful?

Solution

One solution would be extend a common BaseClass Controller for every class authenticated.

This way you can write once.

OTHER TIPS

Module is like a sub-application with separated directory structure. It is not responsible for filtering or checking for permission.

The only vital solution is to define a new abstraction as Ismael proposed.

class ExtendedController
{
    public function rules()
    {
        return array_merge(parent::rules(), array(
           // your rules
        ));
    }
}

Ismael and pestaa choices are very good even fast to implement, nevertheless I always recommend more powerful alternatives like RBAC model. You can find a very good GUI for Yii RBAC in http://code.google.com/p/srbac/

This worked for me:

class extendedController extends baseController
{
    public function accessRules()
    {
        return array_merge(

            // This controller's rules are added first:
            // Allow all users to call the 'hello' action.
            array(
                array('allow',
                    'actions'=>array('hello'), 
                    'users'=>array('*'),
                ),
            ),

            // BaseController rules are added last, especially
            // if the last rule in the baseController denies all
            // users that were not allowed yet.
            parent::accessRules()
        );
    }

    public function actionHello()
    {
        echo('Hello!');
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top