Yii2 使用Event -1 ,如何使用事件

1.首先需要 定义 事件传递的数据格式类:

<?php  
  
namespace myapp\frontend\code\ECM\Customer\events;  
  
use Yii;  
use yii\base\Model;  
use yii\base\Event;  
/**  
 * ContactForm is the model behind the contact form.  
 */  
class MessageEvent extends Event  
{  
    public $message;  
}

在这个 MessageEvent 里面就定义了一个变量  $message

2.

编写事件:   事件只要定义个hello 函数,然后参数为  上面第一步分传递的$event 对象,里面包含$message 参数,如果这个Event执行

那么。将会写入日志。

<?php  
  
namespace myapp\frontend\code\ECM\Customer\events;  
  
use Yii;  
  
/**  
 * ContactForm is the model behind the contact form.  
 */  
class Ha   
{  
    public function hello($event){  
        Yii::info($event->message,'mylog');  
    }  
}

3

绑定和触发事件

<?php  
namespace myapp\frontend\code\ECM\Cms\controllers;  
  
use Yii;  
use myapp\frontend\code\ECM\BaseController;  
  
use myapp\frontend\code\ECM\Customer\events\Ha;  
use myapp\frontend\code\ECM\Customer\events\MessageEvent;  
  
class IndexController extends BaseController  
{  
     
   # 定义Event的名字  
    const EVENT_HELLO = 'my hello';  
      
    public function actionIndex()  
    {  
          
        #定义传递数据的格式 Event  
        $event = new MessageEvent;  
        # 赋值  
        $event->message = 'good';  
        # 绑定事件Event  这个事件对应的是:Ha->hello($event);  
        $this->on(self::EVENT_HELLO, [new \myapp\frontend\code\ECM\Customer\events\Ha(), 'hello']);  
        # 触发事件 ,$event 这个对象传递到  Ha->hello($event);   
        $this->trigger(self::EVENT_HELLO,$event);  
          
        return $this->render('index');  
    }  
      
      
      
      
}

从这里看,貌似没有多大用处,直接作为参数调用就行了,两边都写代码麻烦

但是,事件是可以不再文件的函数内书写绑定,可以在new 对象之后再绑定

$foo = new Foo;  
  
// 处理器是全局函数  
$foo->on(Foo::EVENT_HELLO, 'function_name');  
  
// 处理器是对象方法  
$foo->on(Foo::EVENT_HELLO, [$object, 'methodName']);

也可以在Behavior 行为绑定事件。

譬如在一个类保存的时候可以触发一个 保存后的事件

如果这个类没有绑定事件,那么执行为空

如果绑定,就会执行

1.如果一个Event,被多个类执行,一般使用Behavior的方式进行绑定,譬如  Avtive Record 保存后写入log

这种情况一般是自己写的类,使用别人写的,或者自己写的Event。进行一些处理

2.如果是系统的类,类的事件触发已经写好,但是没有绑定事件,默认什么也没有执行,譬如active Record 的 beforeSave操作

对于这种,我们不能去修改系统的代码,所以,我们可以通过$foo->on()的方式进行绑定,然后在执行save操作,就会触发beforeSave();

当然,我们可以定义一个子类,继承ActiveRecord,然后再里面添加行为。

《Yii2 使用Event -1 ,如何使用事件》有1个想法

树叶的兰花园进行回复 取消回复

电子邮件地址不会被公开。 必填项已用*标注