简体   繁体   中英

How to make roles in yii

So i am new to the yii framework and i am doing this blog style of a website trying to cover most of the features i can think off and the one I am stuck at is the having differnet user roles for example.

Lets say we have a writer and a normal logged in user and i want to make a writer when he go on the article page he can see some buttons while a normal loged in user can only see the comment button.

How do i come up with something to do this inside of the Yii Framework? and tutorials i can find on the internet?

Thank you for your time.

List all roles in User model

class User extends MyModel {

   const ROLE_ADMIN = 1,
      ROLE_AUTHOR = 2,
      ROLE_USER = 3;

Also add role field to user (in database and in model).

In components/UserIdentity.php add some methods

public function isAuthor() {
     return !empty($this->user) && $this->user->role == User::ROLE_AUTHOR;
}

public function isGuest(){
     return empty($this->user);
}

Also, I recommend to add this method to User model:

public function getRole($role = null) {
     $roles = [
         self::ROLE_ADMIN => 'Admin',
         self::ROLE_AUTHOR => 'Author',
         self::ROLE_USER => 'User',
     ];

     if (!is_null($role)) {
         return isset($roles[$role]) ? $roles[$role] : 'Unknown role';
     }

     return $roles;
}

Hello thank you for the help that other people gave me but I have a found aa simple guide which i understood very easily and its very nice to use. you can find the tutorial in the following Link . Thank you For you help guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM