php yii-base-Event类(方法)实例源码

下面列出了php yii-base-Event 类(方法)源码代码实例,从而了解它的用法。

作者:achertovsk    项目:maplocatio   
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;
 }

作者:brucealdridg    项目:yii2-audi   
/**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     Event::on(BaseMailer::className(), BaseMailer::EVENT_AFTER_SEND, function ($event) {
         AuditMail::record($event);
     });
 }

作者:dimit    项目:yii2-listene   
/**
  * 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);
             }
         }
     }
 }

作者:simplato    项目:mediali   
public function init()
 {
     parent::init();
     Event::on(BaseStorage::className(), BaseStorage::EVENT_READFILE, function ($e) {
         $this->addItem($e);
     });
 }

作者:NullRefExce    项目:yii2-cm   
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'];
             });
         }
     }
 }

作者:songhongy    项目:datecente   
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',
     // ];
 }

作者:rajanishtime    项目:basicyi   
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);
     });
 }

作者:testbot    项目:openba   
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);
     });
 }

作者:manyoubaby12    项目:imsho   
/**
  * @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']);
 }

作者:pbabila    项目:bcod   
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);
         }
     }
 }

作者:aekkapu    项目:yii2-myli   
/**
  * (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());
     }
 }

作者:ramialcheik    项目:quickform   
/**
  * 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);
                         }
                     }
                 }
             }
         }
     }
 }

作者:rzan    项目:yii2-sqlogge   
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();
 }

作者:GarenGo    项目:yi   
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
      */
 }

作者:denol    项目:yii2-file-storag   
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;
 }

作者:zarv1    项目:yii2-two-way-syn   
/**
  * 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;
 }

作者:sniv    项目:semant   
public function init()
 {
     parent::init();
     Event::on(View::className(), View::EVENT_BEFORE_RENDER, function (ViewEvent $event) {
         $this->_viewFiles[] = $event->sender->getViewFile();
     });
 }

作者:mithun1200    项目:yii2-usermanag   
public function init()
 {
     parent::init();
     Event::on(Controller::className(), Controller::EVENT_BEFORE_ACTION, function ($event) {
         $event->sender->view->params['pagelabel'] = 'User Management System';
     });
 }

作者:VEKsoftwar    项目:yii2-log-behavio   
/**
  * @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);
 }

作者:timelessmemor    项目:uhkkl   
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]);
     });
 }


问题


面经


文章

微信
公众号

扫码关注公众号