Yii2 behaviors and events

Personal understanding of events and actions

First of all, events and behaviors are the functions that component classes have under the yii2 framework. The component class is an instance of the yii\base\Component class or its subclasses. Therefore, under the yii2 framework, most classes can use events and behaviors.

The event is to bind a callback function to the specified instance or class, when needed, use the trigger to call it. In YII2, yii\base\Controller has built-in beforeAction and afterAction predefined event functions; yii\base\Model has beforeValidate, afterValidate and other predefined event functions. These functions all use trigger to call predefined events.

Behavior is to bind a behavior class to a class or instance. After binding, the instance can call methods and properties in the behavior class. The internal principle of behavior binding is the same as that of event binding, and both use the on method of the component base class. We can override the event method in the behavior class and specify the method to be called by the event. When the component calls this behavior class, the built-in events such as before~ in the component will automatically execute the specified method after rewriting; and for the predefined events that are not in the component, we can use the trigger to call the event, or directly call the custom event The corresponding method name.

//建立一个行为类
class BaseBehavior extends Behavior{
    
    
    public $owner;
    public function events()
    {
    
    
        return [
            ‘beforeValidate’ => 'beforeValidate',
            ‘mine’ =>'formatResult',
        ];
    }
    public function beforeValidate(){
    
    
		//验证前执行的事件
	}
    public function formatResult(){
    
    
   		//我的自定义事件
	}
 }
 //建立一个model类
 class UserModel extends Model{
    
    
	 public function behaviors()
    {
    
    
    	return ['MyBehavior'=>BaseBehavior ::className];
    }
    //如果只想修改beforeValidate事件,可以不使用行为,重写beforeValidate即可
    //也可以在类实例化后,直接使用on方法,设置beforeValidate事件
    public function beforeValidate($action)
	{
    
    
	    if (!parent::beforeValidate($action)) {
    
    
	        return false;
	    }
	    return true;
	}
}
//运行model类
$model = new UserModel ();
//使用on方设置事件
$model->on('beforeValidate',function(){
    
    
                //验证前可进行其他操作,比如检测参数的数量等
            });
$model->validate();//运行该方法之前会调用beforeValidate事件
$model->trigger('mine');//使用trigger调用mine事件
$model->formatResult();//直接调用行为中的方

Some behaviors predefined by Yii2

As long as we set up these behaviors in the controller, we don't need to execute them in the code. When the framework is running, it will automatically execute related methods at the locations where these behaviors are predefined.

Controller behavior
public function behaviors(){
    
    
        $behaviors = parent::behaviors();
        //设置跨域请求相关,一般用在接口类控制器接口的基类中
        $behaviors['cors'] = [
            'class' => \tesoon\filters\Cors::className(),
            'cors' => [
            	//设置允许跨域请求的域名,*表示不限
                'Origin' => ['*'],
                //设置允许的请求方式,*表示不限
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                /*
                浏览器的同源策略,就是出于安全考虑,浏览器会限制从脚本发起的跨域HTTP请求(比如异步请求GET, POST, PUT, DELETE, OPTIONS等等),
                所以浏览器会向所请求的服务器发起两次请求,第一次是浏览器使用OPTIONS方法发起一个预检请求,第二次才是真正的异步请求,
                第一次的预检请求获知服务器是否允许该跨域请求:如果允许,才发起第二次真实的请求;如果不允许,则拦截第二次请求。
                Access-Control-Max-Age用来指定本次预检请求的有效期,单位为秒,在此期间不用发出另一条预检请求。
                等于0时,表示每次异步请求都发起预检请求
                */
                'Access-Control-Max-Age' => 86400,
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Expose-Headers' => ['*'],
                'Access-Control-Allow-Headers' => ['*']
            ],
        ];
        //身份验证
        $behaviors['authenticator'] = [
            'class'=>QueryParamAuth::class,
        ];
        //接口速率限制
        $behaviors['rateLimiter'] = [
            'class' => RateLimiter::className(),
        ];
        //设置控制器返回数据格式,也可以在config中设置
        $behaviors['contentNegotiator'] = [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ],
            ];
		//设置控制器下,方法的执行权限
		//目前很少用到,对于需登录进行的操作,一般在身份认证时,即可阻断,不需要在这里设置
		 $behaviors['access'] = [
			'class' => AccessControl::className(),
            'only' => ['index', 'create', 'update'],
            'rules' => [
                // 允许认证用户
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // 禁止游客用户执行
                [
                        'allow' => true,
                        'actions' => ['logout'],
                        'roles' => ['@'],
                ],
            ], 
		];
         //过滤当前控制器下,方法允许的请求方式   
         $behaviors['verbFilter'] = [
             'class' => VerbFilter::className(),
             'actions' => [
                 'index' => [ 'get'],            //只允许get方式访问
                 'create' => [ 'post'],          //只允许用post方式访问
                 'update' => [ 'post']
             ],
         ];
        return $behaviors;
    }
Model behavior
public function behaviors() {
    
    
        return [
        	//匿名行为,自动添加更新时间戳字段
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['create_time','update_time'],
                    self::EVENT_BEFORE_UPDATE => ['update_time'],
                ],
            ],
        ];
    }

yii\behaviors\AttributeBehavior: When certain events occur, the specified value is automatically assigned to one or more attributes of the AR object.
yii\behaviors\TimestampBehavior: The specified attribute is automatically filled with the current timestamp.
yii\behaviors\BlameableBehavior : Use the current user ID to automatically fill in the specified attributes.
yii\behaviors\SluggableBehavior: Automatically use a value that can be used in the URL to fill the specified attributes.
yii\behaviors\AttributeTypecastBehavior: Provides automatic conversion of model attribute types

Guess you like

Origin blog.csdn.net/u012830303/article/details/110925242