如何理解yii2的 Event?全局绑定,特别疑惑

疑惑不解

这一段的内容 https://github.com/yiisoft/yii2/blob/master/docs/guide/concept-events....,里面一直在不断的强调说事件Event的绑定:

php$foo = new Foo;

// this handler is a global function
$foo->on(Foo::EVENT_HELLO, 'function_name');

// this handler is an object method
$foo->on(Foo::EVENT_HELLO, [$object, 'methodName']);

// this handler is a static class method
$foo->on(Foo::EVENT_HELLO, ['app\components\Bar', 'methodName']);

// this handler is an anonymous function
$foo->on(Foo::EVENT_HELLO, function ($event) {
    // event handling logic
});

问题是

1)这一段代码是放在哪里?放在 public function actionXXX(){}里面吗?
2)我想让除admin的action之外的网站里面所有action在执行前都进行对会员是否登录,已登录会员是否已经创建了日志的检测,如何实现这个?

阅读 6.3k
2 个回答
  • 可以放在执行 Yii::$app->user->login() 执行前进行绑定
  • 如果全局绑定的话,可以放在bootstrap中进行绑定,例如:

\yii\base\Event::on(\yii\web\User::className(), \yii\web\User::EVENT_BEFORE_LOGIN, function($event) { //your logic });

作为 __FresHmaN 的一个补充:

  • 在 advanced-template 中可以在 @app/config/bootstrap.php 中进行绑定, 也可以用下面的方法;
  • 在 basic-template 中可以在 web.php 中设置 Yii::$app->bootstrap;
  • 也可以在 basic-template config 中自行创建 bootstrap_what_ever.php, 并在 web/index.php 中调用。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进