Yii Framework ACF of accessController Simple Privilege Control Operation Example

  • 2021-12-09 08:18:49
  • OfStack

This article illustrates the simple permission control operation of the Yii framework ACF (accessController). Share it 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 2017 Year 2 Month 14 Number can only be accessed 
                  },
                  'denyCallback'=>function($rule,$action){ // Rules against access 
                  },
                  'ips'=>[],// Permissible ip
                  'verbs'=>['GET','POST','DELETE'],// Mode of request 
              ],
        ],
      ],
    ];
  }
  // ...
}

Access rules are set by the following context parameters:

actions: Sets which action matches this rule.

roles: Sets which role matches this rule.

*: Any user, including anonymous and authenticated users.
? Anonymous user.
@: Authenticated users.

ips: Sets which client IP matches this rule.

verbs: Sets which request type (for example, GET, POST) matches this rule.

matchCallback: Specifies an PHP callback to determine that the rule is applied.

denyCallback: The PHP callback is invoked 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 visitors and logged-in users of the blog system

For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Yii framework.


Related articles: