In yii2, event binding is operated through the on method of yii\base\Component. When we define the event, we need to bind a callback function to it.
Look at the example, first write a controller, use on to bind the event, and then use triggle in the method to call
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); } }
to access the index method and get the result of the event. When entering the controller, a time is bound to 'event'. The first parameter of on represents the event name (must be a constant), and the second parameter is the callback function of this event.
(Recommended tutorial: yii framework)
can also be written in the following way:
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 represents this object, 'onTest' Refers to the method of execution. After the event is bound, it is useless if it is not called. At this time, the triggle method in the yii\base\Component class is used to call it.
Extended application of events (parameter passing method)
First define a controller and define and call it. If you want to pass in different parameters, you must The yii\base\Event class is used
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 contains the calling method
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' } }
For more programming related content, please visit the php Chinese websiteProgramming Tutorialcolumn!
The above is the detailed content of How to bind events in yii2.0. For more information, please follow other related articles on the PHP Chinese website!