小編給大家分享一下yii2.0如何綁定事件,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

在yii2中,事件的綁定是通過yii\base\Component的on方法進行操作的,我們在定義事件的同時,需要為其綁定一個回調(diào)函數(shù)。
看下例子,先寫下一個控制器,用on綁定事件,然后在方法里面用triggle調(diào)用
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第一個參數(shù)表示事件名(必須是常量),第二個參數(shù)是這個事件的回調(diào)函數(shù)。
也可以寫成如下的方式:
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’指的是執(zhí)行的方法。事件綁定好后沒有調(diào)用還是沒用,此時用到y(tǒng)ii\base\Compontent類中的triggle方法來調(diào)用了。
事件的擴展運用(參數(shù)的傳入方法)
先定義一個控制器在里面定義加調(diào)用,如果想要傳入不同的參數(shù)就要用到 yii\base\Event 類了
class EventController extends Controller
{
const TEST_USER = 'email'; //發(fā)送郵件
public function init()
{
parent::init();
$msg = new Msg();
$this->on(self::TEST_USER,[$msg,'Ontest'],'參數(shù)Test');
}
public function actionTest()
{
$msgEvent = new MsgEvent();
$msgEvent->dateTime = 'Test時間';
$msgEvent->author = 'Test作者';
$msgEvent->content = 'Test內(nèi)容';
$this->trigger(self::TEST_USER,$msgEvent);
}
}class MsgEvent extends Event
{
public $dateTime; // 時間
public $author; // 作者
public $content; // 內(nèi)容
}msg里面放的是調(diào)用的方法
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內(nèi)容'
print_r($event->data);//輸出'參數(shù)Test'
}
}以上是“yii2.0如何綁定事件”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
新聞標題:yii2.0如何綁定事件-創(chuàng)新互聯(lián)
文章地址:http://chinadenli.net/article14/ccggde.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導航、動態(tài)網(wǎng)站、網(wǎng)站收錄、電子商務、商城網(wǎng)站、全網(wǎng)營銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容