When a class-level event is triggered, event handlers attached
to that class and all parent classes will be invoked.
For example, the following code attaches an event handler to ActiveRecord's
afterInsert event:
php
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
Yii::trace(get_class($event->sender) . ' is inserted.');
});
The handler will be invoked for EVERY successful ActiveRecord insertion.
For more details about how to declare an event handler, please refer to [[Component::on()]].
public static on ( string $class, string $name, callable $handler, mixed $data = null, boolean $append = true ) | ||
$class | string | the fully qualified class name to which the event handler needs to attach. |
$name | string | the event name. |
$handler | callable | the event handler. |
$data | mixed | the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]]. |
$append | boolean | whether to append new event handler to the end of the existing handler list. If `false`, the new handler will be inserted at the beginning of the existing handler list. |
public function init() { parent::init(); if (is_null($this->attribute)) { throw new Exception("Module \"attribute\" attribute must be set"); } if (is_null($this->latitudeAttribute)) { throw new Exception("Module \"latitudeAttribute\" attribute must be set"); } if (is_null($this->longitudeAttribute)) { throw new Exception("Module \"longitudeAttribute\" attribute must be set"); } if (is_null($this->jsonAttribute)) { throw new Exception("Module \"jsonAttribute\" attribute must be set"); } if (is_null($this->class)) { $this->class = __NAMESPACE__ . '\\models\\Locations'; } $location = new $this->class(); $location->setAttributes(['destinationAttribute' => $this->attribute, 'latitudeAttribute' => $this->latitudeAttribute, 'longitudeAttribute' => $this->longitudeAttribute, 'jsonAttribute' => $this->jsonAttribute]); $this->location = $location; Event::on(Locations::className(), Locations::EVENT_ADD_LOCATION, [Locations::className(), 'addLocation']); Event::on(Locations::className(), Locations::EVENT_GET_LOCATION, [Locations::className(), 'getLocation']); return true; }
public function bootstrap($app) { /** @var Module $module */ if ($app->hasModule('cms') && ($module = $app->getModule('cms')) instanceof Module) { $classMap = array_merge($this->classMap, $module->classMap); foreach (array_keys($this->classMap) as $item) { $className = '\\nullref\\cms\\models\\' . $item; $cmsClass = $className::className(); $definition = $classMap[$item]; Yii::$container->set($cmsClass, $definition); } if ($app instanceof WebApplication) { $prefix = $app->getModule('cms')->urlPrefix; $app->urlManager->addRules([Yii::createObject(['class' => PageUrlRule::className(), 'pattern' => $prefix . '/<route:[_a-zA-Z0-9-/]+>'])]); if (!isset($app->controllerMap['elfinder-backend'])) { $app->controllerMap['elfinder-backend'] = ['class' => 'mihaildev\\elfinder\\Controller', 'user' => 'admin', 'access' => ['@'], 'disabledCommands' => ['netmount'], 'roots' => [['path' => 'uploads', 'name' => 'Uploads']]]; } $app->i18n->translations['cms*'] = ['class' => PhpMessageSource::className(), 'basePath' => '@nullref/cms/messages']; } if (YII_ENV_DEV) { Event::on(Gii::className(), Gii::EVENT_BEFORE_ACTION, function (Event $event) { /** @var Gii $gii */ $gii = $event->sender; $gii->generators['block-migration-generator'] = ['class' => 'nullref\\cms\\generators\\block_migration\\Generator']; $gii->generators['block-generator'] = ['class' => 'nullref\\cms\\generators\\block\\Generator']; $gii->generators['pages-migration-generator'] = ['class' => 'nullref\\cms\\generators\\pages_migration\\Generator']; }); } } }
/** * @inheritdoc */ public function init() { parent::init(); Event::on(BaseMailer::className(), BaseMailer::EVENT_AFTER_SEND, function ($event) { AuditMail::record($event); }); }
/** * Init component */ public function init() { parent::init(); if (is_string($this->listeners)) { $listeners = (include_once Yii::getAlias($this->listeners) . '.php'); } elseif (is_array($this->listeners)) { $listeners = $this->listeners; } else { throw new Exception('Create ' . $this->listeners . '.php file or set array, it is requered! $listeners have to get array!'); } foreach ($listeners as $key => $listener) { foreach ($listener as $objects) { if (true === is_array($objects) && false === is_object($objects[0]) && false === class_exists($objects[0])) { $objects = function () use($objects) { $component = eval('return ' . $objects[0] . ';'); call_user_func_array(array($component, $objects[1]), func_get_args()); }; } if (!is_array($key)) { //Global event Yii::$app->on($key, $objects); } else { Event::on($key[0], $key[1], $objects); } } } }
public function init() { parent::init(); Event::on(BaseStorage::className(), BaseStorage::EVENT_READFILE, function ($e) { $this->addItem($e); }); }
public function init() { $subscribers = $this->getSubscribers(); foreach ($subscribers as $subscriberClassName) { /** @var SubscriberInterface $subscriber */ $subscriber = new $subscriberClassName(); $events = $subscriber->getSubscribedEvents(); foreach ($events as $event => $callback) { if (is_array($callback)) { list($callback, $layer) = $callback; } if (isset($layer)) { if (is_array($layer)) { //in future We can declare Event as key of array if nessesary Event::on($layer[0], $event, [$subscriber, $callback]); } else { \Yii::$app->{$layer}->on($event, [$subscriber, $callback]); } } else { \Yii::$app->on($event, [$subscriber, $callback]); } unset($layer); } } }
public function events() { // 查询事件 // Event::on( // ActiveRecord::className(), // ActiveRecord::EVENT_AFTER_FIND, [$this, 'afterFind'] // ); // 写入事件 Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, [$this, 'afterInsert']); // 更新事件 Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_UPDATE, [$this, 'afterUpdate']); // 删除事件 Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_DELETE, [$this, 'afterDelete']); // 后台登录事件 Event::on(\service\models\LoginForm::className(), \service\models\LoginForm::EVENT_LOGIN_AFTER, [$this, 'afterBackendLogin']); // 后台退出事件 Event::on(\service\models\LoginForm::className(), \service\models\LoginForm::EVENT_LOGOUT_BEFORE, [$this, 'beforeBackendLogout']); return []; // return [ // ActiveRecord::EVENT_AFTER_FIND => 'afterFind', // ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert', // ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate', // ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete', // \backend\models\LoginForm::EVENT_LOGIN_AFTER => 'afterBackendLogin', // \backend\models\LoginForm::EVENT_LOGOUT_AFTER => 'afterBackendLogout', // ]; }
public function build() { \yii\base\Event::on(\denoll\filekit\Storage::className(), \denoll\filekit\Storage::EVENT_BEFORE_SAVE, function ($event) { /** @var \denoll\filekit\Storage $storage */ $storage = $event->sender; if (!$storage->getFilesystem()->has('.dirindex')) { $storage->getFilesystem()->write('.dirindex', 1); $dirindex = 1; } else { $dirindex = $storage->getFilesystem()->read('.dirindex'); } if ($storage->maxDirFiles !== -1) { if ($storage->getFilesystem()->has($dirindex)) { $filesCount = count($storage->getFilesystem()->listContents($dirindex)); if ($filesCount > $storage->maxDirFiles) { $dirindex++; $storage->getFilesystem()->createDir($dirindex); } } else { $storage->getFilesystem()->createDir($dirindex); } } }); $client = new \Sabre\DAV\Client(['baseUri' => 'https://webdav.yandex.ru']); $client->addCurlSetting(CURLOPT_SSL_VERIFYPEER, false); $client->addCurlSetting(CURLOPT_HTTPHEADER, ['Authorization: OAuth TOKENTOKENTOKEN', 'Accept: */*', 'Host: webdav.yandex.ru']); $adapter = new WebDAVAdapter($client, '/'); $flysystem = new Filesystem($adapter); if (!$flysystem->has($this->pathPrefix)) { $flysystem->createDir($this->pathPrefix); } $adapter->setPathPrefix($this->pathPrefix); return $flysystem; }
public function init() { parent::init(); Event::on(Controller::className(), Controller::EVENT_BEFORE_ACTION, function ($event) { $event->sender->view->params['pagelabel'] = 'User Management System'; }); }
/** * @inheritdoc */ public function init() { parent::init(); $this->mailer = Instance::ensure($this->mailer, 'im\\users\\components\\UserMailerInterface'); Event::on(User::className(), User::EVENT_BEFORE_REGISTRATION, [$this, 'beforeUserRegistration']); Event::on(User::className(), User::EVENT_AFTER_REGISTRATION, [$this, 'afterUserRegistration']); }
public function init() { parent::init(); Event::on(View::className(), View::EVENT_BEFORE_RENDER, function (ViewEvent $event) { $this->_viewFiles[] = $event->sender->getViewFile(); }); }
public function bootstrap($app) { Event::on(ActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_TRANCINSERT, function ($event) { TcEventAction::EventActionAfterTrancInsert($event); }); Event::on(ActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_TRANCUPDATE, function ($event) { TcEventAction::EventActionAfterTrancUpdate($event); }); Event::on(ActiveRecord::classname(), BaseActiveRecord::EVENT_AFTER_INSERT, function ($event) { TcEventAction::EventActionCreate($event); }); Event::on(ActiveRecord::classname(), BaseActiveRecord::EVENT_AFTER_UPDATE, function ($event) { TcEventAction::EventActionUpdate($event); }); Event::on(ActiveRecord::classname(), AppActiveRecord::EVENT_BEFORE_PUBLISH, function ($event) { TcEventAction::EventActionBeforePublish($event); }); Event::on(ActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_PUBLISH, function ($event) { TcEventAction::EventActionAfterPublish($event); }); Event::on(AppActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_SOFTDELETE, function ($event) { TcEventAction::EventActionSoftDelete($event); }); Event::on(AppActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_UNPUBLISH, function ($event) { TcEventAction::EventActionUnpublish($event); }); }
public function init() { $command = null; if ($this->onInsert) { Event::on(ActiveRecord::className(), ActiveRecord::EVENT_BEFORE_INSERT, function ($event) { $db = $event->sender->db; $values = $event->sender->getDirtyAttributes(); $command = $db->createCommand()->insert($event->sender->tableName(), $values)->rawSql; }); } if ($this->onUpdate) { Event::on(ActiveRecord::className(), ActiveRecord::EVENT_BEFORE_UPDATE, function ($event) { $db = $event->sender->db; $values = $event->sender->getDirtyAttributes(); $condition = $event->sender->getOldPrimaryKey(true); $command = $db->createCommand()->update($event->sender->tableName(), $values, $condition)->rawSql; }); } if ($this->onDelete) { Event::on(ActiveRecord::className(), ActiveRecord::EVENT_BEFORE_DELETE, function ($event) { $db = $event->sender->db; $values = $event->sender->getDirtyAttributes(); $condition = $event->sender->getOldPrimaryKey(true); $command = $db->createCommand()->delete($event->sender->tableName(), $condition)->rawSql; }); } Log::save($command); return parent::init(); }
/** * (non-PHPdoc) * * @see \yii\base\BootstrapInterface::bootstrap() * @param $app \yii\web\Application */ public function bootstrap($app) { session_name('session-id'); /* @var $cfg \frontend\components\Configuration */ $cfg = $app->mycfg; date_default_timezone_set($cfg->system->timezone); $app->language = $cfg->system->language; // inject into app // TODO: mariadb, postgres, cubrid, oracle, mssql try { switch ($cfg->database->format) { case 'mysql': $app->db->dsn = "mysql:host={$cfg->database->host};dbname={$cfg->database->dbname}"; $app->db->username = $cfg->database->login; $app->db->password = $cfg->database->password; break; case 'sqlite': $app->db->dsn = "sqlite:{$cfg->database->filename}"; break; } if ($cfg->getVersion() != $cfg->system->version) { //redirect to migration, as user config doesnot contain matching version Event::on('app\\components\\Controller', Controller::EVENT_BEFORE_ACTION, function ($e) { \Yii::$app->response->redirect(['install/migrate']); return false; }); } } catch (\Exception $e) { $app->session->setFlash('db_init', $e->getMessage()); } }
/** * Attaches global and class-level event handlers from sub-modules * * @param \yii\base\Application $app the application currently running */ public function attachEvents($app) { foreach ($this->getModules() as $moduleID => $config) { $module = $this->getModule($moduleID); if ($module instanceof EventManagerInterface) { /** @var EventManagerInterface $module */ foreach ($module->attachGlobalEvents() as $eventName => $handler) { $app->on($eventName, $handler); } foreach ($module->attachClassEvents() as $className => $events) { foreach ($events as $eventName => $handlers) { foreach ($handlers as $handler) { if (is_array($handler) && is_callable($handler[0])) { $data = isset($handler[1]) ? array_pop($handler) : null; $append = isset($handler[2]) ? array_pop($handler) : null; Event::on($className, $eventName, $handler[0], $data, $append); } elseif (is_callable($handler)) { Event::on($className, $eventName, $handler); } } } } } } }
public function actionEvent() { $dog = new Dog(); //$this->on('cat_shout', [$mouse , 'run']); //错误: 绑定事件的on() 必须是来自触发事件的对象或类 $cat = new Cat(); $cat2 = new Cat(); $cat->on('cat_shout', [$dog, 'look']); //对象 $mg = new Messages(); $mg->message = "should I catch the cat or the mouse?"; $cat->on('cat_shout', [$dog, 'think'], $mg); //出入信息,传入信息必须是Event或其子类 $cat->off('cat_shout', [$dog, 'think']); //关闭事件 $cat->on('cat_shout', ['app\\events\\Mouse', 'run'], '', false); //静态函数. Event::on(Cat::className(), 'cat_shout', function ($event) { echo "类级别事件,所有猫都生效.<br>"; echo '<pre>'; print_r($event->sender); echo '</pre>'; }); $cat->shout(); $cat2->shout(); //全局事件 Yii::$app->on(Application::EVENT_AFTER_REQUEST, function ($event) { echo get_class($event->sender); // 显示 "app\components\Foo" }); /* * 这个事件(Application::EVENT_AFTER_REQUEST)在请完成后会触发 * 如果是自己写的全局事件触发使用:Yii::$app->trigger */ }
public function bootstrap($app) { Event::on(RatingModule::className(), RatingModule::EVENT_RATING_ADD, function ($event) { $torrent = \Yii::$app->db->cache(function ($db) use($event) { return Torrent::findOne($event->recordId); }); $torrent->rating_avg = ($torrent->rating_votes * $torrent->rating_avg + $event->rating) / ($torrent->rating_votes + 1); $torrent->rating_votes = $torrent->rating_votes + 1; $torrent->save(false); }); Event::on(ComplainModule::className(), ComplainModule::EVENT_COMPLAINT_ADD, function ($event) { if ($event->total >= \Yii::$app->params['numberComplaintsToHide'] && ($event->type === Complaint::TYPE_FAKE || $event->type === Complaint::TYPE_VIRUS)) { $torrent = \Yii::$app->db->cache(function ($db) use($event) { return Torrent::findOne($event->recordId); }); $torrent->visible_status = Torrent::VISIBLE_STATUS_DIRECT; $torrent->save(false); } }); Event::on(CommentModule::className(), CommentModule::EVENT_COMMENT_ADD, function ($event) { $torrent = \Yii::$app->db->cache(function ($db) use($event) { return Torrent::findOne($event->recordId); }); $torrent->comments_count = $torrent->comments_count + 1; $torrent->save(false); }); }
/** * Attach two-way sync needed behaviors for REST action * @param ActionEvent $event * @return bool * @throws NotSupportedException */ public function beforeRestAction(ActionEvent $event) { /** @var Action $action */ $action = $event->action; Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_INIT, [$this, 'makeModelSyncable'], null, false); switch (get_class($action)) { case IndexAction::className(): $action->attachBehavior('indexLatest', IndexLatestBehavior::className()); break; case CreateAction::className(): // nothing to attach on create for now // TODO: check is needed to behave something here break; case UpdateAction::className(): $action->attachBehavior('updateConflict', UpdateConflictBehavior::className()); break; default: // TODO: implement custom new so called 'TwoWaySync action' stub for future custom actions // TODO: and add method attachSyncBehaviors() // $action->attachSyncBehaviors(); // throw new NotSupportedException("Not implemented yet"); break; } return $event->isValid; }
public function init() { parent::init(); //вешаем на событие удаления пользователя удаление всех его назначений в acl Event::on(User::class, User::EVENT_USER_DELETE, function (UserEvent $event) { return $this->revokeAll($event->user->id); }); }
public function init() { parent::init(); Event::on(self::className(), self::EVENT_AFTER_INSERT, function ($event) { $message = $event->sender; Yii::$app->tuisongbao->triggerEvent(self::EVENT_NEW_MESSAGE, $message->toArray(), [self::CHANNEL_GLOBAL . $message->accountId]); }); }
/** * @inheritdoc * * @param ActiveRecord $owner * * @throws ErrorException */ public function attach($owner) { if (!self::$_eventSwitched) { Event::on($owner->className(), VekActiveRecord::EVENT_TO_SAVE_MULTIPLE, [self::className(), 'logToSaveMultiple']); Event::on($owner->className(), VekActiveRecord::EVENT_SAVED_MULTIPLE, [self::className(), 'logSavedMultiple']); } parent::attach($owner); }
public function bootstrap($app) { $customerClass = Kiwi::getCustomerClass(); Event::on($customerClass, $customerClass::EVENT_INIT, function ($event) { /** @var \yincart\customer\models\Customer $customer */ $customer = $event->sender; $customer->attachBehavior('group', Kiwi::getGroupBehaviorClass()); }); }
public function attach($owner) { if (!$owner instanceof UpdateAction) { throw new InvalidParamException(__CLASS__ . ' behavior can be attached only to instance of \\yii\\rest\\UpdateAction'); } parent::attach($owner); Event::on(ActiveRecord::className(), ActiveRecord::EVENT_INIT, [$this, 'onActiveRecordInit']); $owner->controller->on(Controller::EVENT_AFTER_ACTION, [$this, 'handleConflict'], null, false); }
protected function registerEvents() { // Register Global Event Handlers if (!empty($this->events)) { foreach ($this->events as $event) { Event::on($event['class'], $event['event'], $event['callback']); } } }
/** * 绑定事件处理程序 (扩展YII事件机制,在PHP请求生命周期类,同一个事件处理程序只能注册一次) * @param type $class * @param type $name * @param type $handler * @param type $handlerId * @param type $data * @param type $append * @return type */ public static function on($class, $name, $handler, $handlerId, $data = null, $append = true) { //保证同一个ID的Hanlder只注册一次 if (isset(static::$_eventDic[$name][$class][$handlerId])) { return; } static::$_eventDic[$name][$class][$handlerId] = [$handlerId]; Event::on($class, $name, $handler, $data, $append); }
public static function specialEventCallback($className, callable $callback) { /** @var Events $eventsModel Events model instance for determining handlers*/ $eventsModel = Events::findByClassName($className); if ($eventsModel === null) { throw new Exception("No such event for this class " . $className); } Event::on($eventsModel->owner_class_name, $eventsModel->event_name, $callback); }
public function bootstrap($app) { Event::on(ActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_TRANCINSERT, function ($event) { TcEventAction::EventActionAfterTrancInsert($event); }); Event::on(ActiveRecord::classname(), AppActiveRecord::EVENT_AFTER_TRANCUPDATE, function ($event) { TcEventAction::EventActionAfterTrancUpdate($event); }); }
public function bootstrap($app) { Event::on('yii\\i18n\\GettextMessageSource', GettextMessageSource::EVENT_MISSING_TRANSLATION, [$this, 'onMissingTranslation']); Event::on('yii\\i18n\\DbMessageSource', GettextMessageSource::EVENT_MISSING_TRANSLATION, [$this, 'onMissingTranslation']); $timezone = P::$app->getLocale()->detectTimezone(P::$app->timeZone); P::$app->setTimeZone($timezone); $locale = P::$app->getLocale()->detectLocale(P::$app->language); P::$app->setLanguage($locale); }
public function init() { Event::on(View::className(), View::EVENT_END_PAGE, function ($event) { if (!$this->isRendered) { $this->getApi()->render(); $this->isRendered = true; } }); }
protected function configureEventHandlers() { if ($this->setScenario) { foreach (self::$_setScenarioEvents as $eventName) { Event::on($this->className, $eventName, function ($event) { $event->sender->scenario = self::SCENARIO_IMPORT; }); } } }