yii2.0怎么绑定事件

王林
王林原创
2020-02-17 14:20:421832浏览

在yii2中,事件的绑定是通过yii\base\Component的on方法进行操作的,我们在定义事件的同时,需要为其绑定一个回调函数。

看下例子,先写下一个控制器,用on绑定事件,然后在方法里面用triggle调用

namespace backend\controllers;

use yii\web\Controller;

class EventController extends Controller
{
   const TEST_EVENT = 'event';

    public function init()
    {
        parent::init();
        $this->on(self::TEST_EVENT,function(){echo '这个一个事件测试。。。';});
    }


    public function actionIndex()
    {
        $this->trigger(self::TEST_EVENT);
    }
}

访问index方法后得到事件的结果。在进入控制器的时候就给‘event’绑定了一个时间,on第一个参数表示事件名(必须是常量),第二个参数是这个事件的回调函数。

(推荐教程:yii框架

也可以写成如下的方式:

namespace backend\controllers;

use yii\web\Controller;

class EventController extends Controller
{
   const TEST_EVENT = 'event';

    public function init()
    {
        parent::init();
        $this->on(self::TEST_EVENT,[$this,'onTest']);
    }


    public function onTest()
    {
        echo '这个一个事件测试。。。';
    }

    public function actionIndex()
    {
        $this->trigger(self::TEST_EVENT);
    }
}

$this表示的是本对象,‘onTest’指的是执行的方法。事件绑定好后没有调用还是没用,此时用到yii\base\Compontent类中的triggle方法来调用了。

事件的扩展运用(参数的传入方法)

先定义一个控制器在里面定义加调用,如果想要传入不同的参数就要用到 yii\base\Event 类了

class EventController extends Controller
{
    const TEST_USER = 'email'; //发送邮件
    public function init()
    {
        parent::init();
        $msg = new Msg();
        $this->on(self::TEST_USER,[$msg,'Ontest'],'参数Test');  
    }
    public function actionTest()
    {
        $msgEvent = new MsgEvent();
        $msgEvent->dateTime = 'Test时间';
        $msgEvent->author = 'Test作者';
        $msgEvent->content = 'Test内容';
        $this->trigger(self::TEST_USER,$msgEvent);
    }
}
class MsgEvent extends Event
{
    public $dateTime;   // 时间
    public $author;     // 作者
    public $content;    // 内容

}

msg里面放的是调用的方法

class Msg extends ActiveRecord
{
    public function onTest($event) //$event是yii\base\Event的对象
    {
        print_r($event->author);//输出'Test作者'
        print_r($event->dateTime);//输出'Test时间'
        print_r($event->content);//输出'Test内容'
        print_r($event->data);//输出'参数Test'

    }
}

更多编程相关内容学习,请访问php中文网编程教程栏目!

以上就是yii2.0怎么绑定事件的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。