PHP code example of jlorente / yii2-roles

1. Go to this page and download the library: Download jlorente/yii2-roles library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jlorente / yii2-roles example snippets


return [
    //Other configurations
    'modules' => [
        //Other modules
        'roles' => [
            'class' => 'jlorente\roles\Module'
             //options
             , 'user' => 'jlorente\roles\web\User'
             , 'roles' => ['Admin', 'User', 'Teacher']
             , 'matchAgainstSession' => false
         ]
    ],
    'bootstrap' => [
        //Other bootstrapped modules
        , 'roles'
    ]
]


namespace common\models;

use jlorente\roles\models\RoleableTrait;
use jlorente\roles\models\RoleableInterface;
 
class User extends yii\db\ActiveRecord implements RoleableInterface {
    
    use RoleableTrait;

    //class content...
}

$user = new User();
jlorente\roles\models\Role::sAssign($user, 'Admin');
jlorente\roles\models\Role::sAssign($user, 'User');
$user->save();


namespace frontend\controllers;

use yii\helpers\ArrayHelper;
use jlorente\roles\filters\AccessControl;
 
class SomeController extends yii\web\Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
                    'access' => [
                        'class' => AccessControl::className(),
                        'rules' => [
                            [
                                'actions' => ['create', 'update', 'delete'],
                                'allow' => true,
                                'roles' => ['@'],
                                'userRoles' => ['Admin']
                            ],
                            [
                                'actions' => ['index', 'read'],
                                'allow' => true,
                                'roles' => ['@'],
                                'userRoles' => ['Admin', 'User'],
                                'matchAgainstSession' => true
                            ]
                        ],
                    ]
        ]);
    }
}

class LoginForm extends Model {

    public $user;
    public $username;
    public $password;
    public $rememberMe = true;

    //Class content....

    public function login() {
        if ($this->validate()) {
            Yii::$app->user->setRolesAsTag('Admin');
            $result = \Yii::$app->user->login($this->user, $this->rememberMe ? 3600 * 24 * 30 : 0);
            return $result;
        } else {
            return false;
        }
    }
}

define('ROLE_ADMIN', 'Admin');
define('ROLE_DIRECTOR', 'Director');
define('ROLE_USER', 'User');
bash
$ php composer.phar