Behaviours or filters - how to use for specific controllers

I want to add the following code only to one component named "LoginRequirement" and i want to add "LoginRequirement" as behaviour or filter to any controller that i want to redirect all not-loggedin users.

Answer to this question will really help me understand behaviours and filters.

( Note, i don’t want to use AuthManager for this )




if (Yii::app()->user->isGuest) {

    Yii::app()->user->loginRequired();

}



I’ve done it like this, is it ok? Or better place to put this?


    protected function beforeAction($action)

    {

        Yii::app()->user->needsLogin();

        return true;

    }

and needsLogin function is:


if (Yii::app()->user->isGuest) {

    Yii::app()->user->loginRequired();

}

I think better way is to use access control filter:




    public function filters() {

        return array(

            'accessControl',

        );

    }


    public function accessRules() {

        return array(

            array('allow',

                'users'=>array('@'),

            ),

            array('deny'),

        );

    }



the code above you must put in your controller class. It means:

[list=1]

[*]Use AccessControllFilter (first function)

[*]Allow any logged user to access actions of this controller (first access rule)

[*]Disallow anybody else (second access rule) - this should redirect user to login page defined in user component

[/list]

Using access rules is more flexible and you do not have to code much, rather configure access.

Thank you very much! I thought that i could only use those access rules with sql database, sqlite or phpauth… and since I don’t understand the motivation behind authmanager: As far as i see i have to revoke roles for a user and save()!!! after they logout. Loading and saving continuously is frightening. That’s why i tried to stay away from it. But i see that by using accessControl, i don’t have to use roles at all! Thank you!

There’s absolutely no need for doing that. Revoke rules from users only when you want to revoke them permanently.