简单理解 yii的 hehavior 就是代码实现了php54的 trait 特性

创建一个hehavior

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
use Yii;
use yii\base\ActionEvent;
use yii\base\Behavior;
use yii\web\Controller;


class NoCsrf extends Behavior
{
    public $actions = [];
    public $controller;
    public function events()
    {
        return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
    }
    public function beforeAction($event)
    {
        $action = $event->action->id;
        if(in_array($action, $this->actions)){
        	$this->controller->enableCsrfValidation = false;
        }
    }    
}

在controller中调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php

    public function behaviors()
    {
        return [
            'csrf' => [
                'class' => NoCsrf::className(),
                'controller' => $this,
                'actions' => [
                    'action-name'
                ]
            ]
        ];
    }

这种方法是将控制器中指定的路由方法不经过csrf验证,如果是全局关闭csrf验证的话直接在 controller 添加

1
2
//关闭csrf验证
public $enableCsrfValidation = false;

原文地址