yii2.0怎么绑定事件

广告:宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取~~~

yii2.0怎么绑定事件

在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'    }}
登录后复制

更多编程相关内容学习,请访问9543建站博客编程教程栏目!

以上就是yii2.0怎么绑定事件的详细内容,更多请关注9543建站博客其它相关文章!

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。
作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:有一套thinkphp源码怎么使用
下一篇:微信小程序简单实现form表单获取输入数据实例分享

发表评论

关闭广告
关闭广告