yii2 Event 使用2


这里说的是通过行为的方式绑定事件


1.定义行为事件类: MyBehavior.php

<?php
namespace myapp\frontend\code\ECM\Customer\events;

use yii\db\ActiveRecord;
use yii\base\Behavior;
use myapp\frontend\code\ECM\Cms\controllers\IndexController;
class MyBehavior extends Behavior
{
    // 其它代码
	const EVENT_HELLO = 'myhello';
	
    public function events()
    {
        return [
            self::EVENT_HELLO => 'hello',
        ];
    }

    public function hello($event)
    {
        \Yii::info($event->message,'mylog');
    }
}
?>


2.定义数据格式类:

<?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;
}


3.在行为函数中绑定定义的   行为事件

<?php
namespace myapp\frontend\code\ECM\Cms\controllers;

use Yii;
use myapp\frontend\code\ECM\BaseController;
use myapp\frontend\code\ECM\Customer\events\MyBehavior;
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 behaviors()
    {
        return [
           
            # 命名行为, 绑定行为事件
			# 绑定后 会通过这个类的events()  返回所有的事件数组,然后全部绑定。
			# 道理就是:通过行为的方式绑定对应的event , 和on函数绑定一个原理
            'myBehavior2' => MyBehavior::className(),
	
        ];
    }
	
    public function actionIndex()
    {
		
		#定义传递数据的格式 Event
		$event = new MessageEvent;
		# 赋值
        $event->message = 'good';
		
		# 触发事件 
		# 这里已经不需要on绑定,因为在行为中已经绑定完成
		$this->trigger(MyBehavior::EVENT_HELLO,$event);
		
        return $this->render('index');
    }
	
	
	
	
}

















4.打印日志查看:tail -f  app/runtime/logs/my.log

2015-11-17 11:50:54 Array[info][mylog] good
    in /www/web/develop/test/erp/myapp/frontend/code/ECM/Customer/events/MyBehavior.php:21
    in /www/web/develop/test/erp/myapp/frontend/code/ECM/Cms/controllers/IndexController.php:36

已经输出对应的  $EventMessage->mesage值。

good!











你可能感兴趣的:(yii2 Event 使用2)