Yii framework ACF (access controller) simple permission control operation example

Time:2020-1-13

This paper gives an example of the access controller (ACF) of Yii framework. To share with you for your reference, as follows:

use yii\filters\AccessControl;
class SiteController extends Controller
{
  public function behaviors()
  {
    return [
      'access' =>[
        'class' => AccessControl::className(),
        'rules' => [
          [
            'allow' => true,
            'actions' => ['index', 'view'],
            'roles' => ['?'],
          ],
          [
            'allow' => true,
            'actions' => ['view','index','create','update'],
            'roles' => ['@'],
          ],
            [
              'actions' => ['special-callback'],
              //'only' => ['special-callback'],
              'allow' => true,
              'matchCallback'=>function($rule,$action){
                Return date ('y-m-d ') = =' 2017-02-14 '; // only accessible on February 14, 2017
              },
              'denycallback' = > function ($rule, $action) {// access forbidden rule
              },
              'IPS' = > [], // allowed IP
              'verbs' = > ['Get', 'post', 'Delete'], // request method
            ],
        ],
      ],
    ];
  }
  // ...
}

Access rules are set by the following context parameters:

actions: set which action matches this rule.

roles: set which role matches this rule.

*: any user, including anonymous and authenticated users.
?: anonymous user.
@: authenticated user.

ips: set which client IP matches this rule.

verbs: set which request type (for example: get, post) matches this rule.

matchCallback: specifies a PHP callback to make sure the rule is applied.

denyCallback: PHP callback, which is called when the rule prohibits access.


public function actionSpecialCallback()
{
  return $this->render('happy-halloween');
}

The above code can be used to control the relevant permissions of the visitors and login users of the blog system

For more information about the content of Yii, please refer to the following topics: introduction to Yii framework and summary of common skills, summary of PHP excellent development framework, basic course of smart template introduction, introduction to PHP object-oriented programming, summary of PHP string usage, introduction to PHP + MySQL database operation and PHP common database operation Skills summary

I hope that this article will be helpful for you to Design PHP program based on Yii framework.