Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Powerful role-based access control in Yii

Wednesday, May 30th, 2012 by Servage

I would like to show a few examples on role based access control in Yii. Yii is a very robust and feature-rich opensource PHP framework, and solves many traditional problems in a clean and fully object-oriented way.

Have a look at your current framework and how you use access control, then take a look at these examples for Yii:

$auth=Yii::app()->authManager;

$auth->createOperation('createPost','create a post');
$auth->createOperation('readPost','read a post');
$auth->createOperation('updatePost','update a post');
$auth->createOperation('deletePost','delete a post');

$bizRule='return Yii::app()->user->id==$params["post"]->authID;';
$task=$auth->createTask('updateOwnPost','update a post by author himself',$bizRule);
$task->addChild('updatePost');

$role=$auth->createRole('reader');
$role->addChild('readPost');

$role=$auth->createRole('author');
$role->addChild('reader');
$role->addChild('createPost');
$role->addChild('updateOwnPost');

$role=$auth->createRole('editor');
$role->addChild('reader');
$role->addChild('updatePost');

$role=$auth->createRole('admin');
$role->addChild('editor');
$role->addChild('author');
$role->addChild('deletePost');

$auth->assign('reader','readerA');
$auth->assign('author','authorB');
$auth->assign('editor','editorC');
$auth->assign('admin','adminD');

You might have noticed that these examples are so straight forward that no detailed explanation is required, since the method names say exactly what they do.

Note the use of business rules

if(Yii::app()->user->checkAccess('createPost')) {
    // create post
}

$params=array('post'=>$post);
if(Yii::app()->user->checkAccess('updateOwnPost',$params)) {
    // update post
}

Yii features a lot of powerful access control functionality. Check out the documentation on this here.

Powerful role-based access control in Yii, 4.1 out of 5 based on 8 ratings
Categories: Tips & Tricks

Keywords: ,

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.