在YII2中,事件的綁定是通過yiibasecomponent的on方法進行操作的,我們在定義事件的同時,需要為其綁定一個回調函數。
看下例子,先寫下一個控制器,用on綁定事件,然后在方法里面用triggle調用
namespace?backendcontrollers; use?yiiwebController; 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?backendcontrollers; use?yiiwebController; 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’指的是執行的方法。事件綁定好后沒有調用還是沒用,此時用到yiibaseCompontent類中的triggle方法來調用了。
事件的擴展運用(參數的傳入方法)
先定義一個控制器在里面定義加調用,如果想要傳入不同的參數就要用到 yiibaseEvent 類了
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是yiibaseEvent的對象 ????{ ????????print_r($event->author);//輸出'Test作者' ????????print_r($event->dateTime);//輸出'Test時間' ????????print_r($event->content);//輸出'Test內容' ????????print_r($event->data);//輸出'參數Test' ????} }
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END