tp5模型事件

可以先建一配置文件auth.php

<?php

return [
    'index' => [
        ['after_update' => ['apply_verify|check_verify' => 1],'model'=>'user'],

    ],
    'purchase' => [
        ['after_update' => ['purchase_status' => 1]],
    ],
    'notice' => [
        ['after_update' => ['submit' => 1]],
    ],

];

再写个基类模型

<?php
namespace app\common\model;
use think\Model;

class Base extends Model{
	protected static function init()
    {
    	//当前模型	
        $model = strtolower(basename(str_replace('\\', '/', get_called_class()), '.php'));
        //配置信息
        $config = array_change_key_case(config('auth'), CASE_LOWER);
        //当前模型配置
        $config_data = isset($config[$model]) ? $config[$model] : [];
        //事件回调
         //事件回调
        if(!$config_data || !is_array($config_data)) {
        	return;
        }
        //标签位
        $field = array_unique(array_map('key', $config_data));
        //更新后事件
        if(in_array('after_update',$field)) {
            self::event('after_update', function ($user) use($config_data) {
                self::updateStatus($user ? $user->toArray() : [], "after_update", $config_data);
            });
        }
        //插入后事件
        if (in_array('after_insert', $field)) {
           self::event('after_insert', function ($user) use($config_data) {
               self::updateStatus($user ? $user->toArray() : [], 'after_insert', $config_data);
            });

        }
    }   
    /**
     * 回调操作
     * @param  array   $data  数组
     * @param  string $field  标签
     * @param  array $config_data 配置信息
     * @return mixed
     */
    static public function updateStatus($data = [],$field = "after_update",$config_data = []) {
        try{
       	    $value = array_column($config_data,$field);
	        if(!$value || empty($data)) {
	            return;
	        }
	        //当前标签位配置
	        $value = end($value); 
	        //所有状态   
	        $arr = explode('|',key($value));
	        //当前监听的状态	
	        $field_status = key(array_intersect_key(array_flip($arr),$data);
	        if(isset($data[$field_status]) && $data[$field_status] == end($value)) {
	            //\push\Send::$model($data);
	            echo 11;exit;
	        }
        }catch(\Exception $e) {
       		$this->error = $e->getMessage();
       		return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_20521363/article/details/81279316
tp5