There are two modules - Comments and Pages with their structure, i.e. the implementation is not standard as default in Yii2. Respectively two controllers

class CommentsController extends BaseController { public function actionIndex() { return $this->render('index'); } } Event::on(PagesController::className(), PagesController::EVENT_GET_COMMENTS, function ($event) { echo 'comments'; }); 

well and similarly for Pages

 class PagesController extends BaseController { const EVENT_GET_COMMENTS = ''; public function actionIndex() { $this->trigger(self::EVENT_GET_COMMENTS); return $this->render('index'); } } 

In theory, when calling the Pages controller, the index action should trigger the EVENT_GET_COMMENTS event and output comments , but this does not happen :(

  • Are you sure that the handler is generally installed? if everything is connected via psr, the CommentsController file code will not be loaded until you explicitly use this CommentsController. - etki
  • Actually this is the problem, but I don’t know how to solve it - Just a guest
  • You need to announce a subscription to an event somewhere earlier. Meaning to declare it in the controller, which will not even run at this event? And in general: why try to build your bikes with good frameworks and not use standard solutions for such things? - Michael Sivolobov

1 answer 1

You have 3 ways:

# 1 (globally):

  1. Create a component with the necessary logic
  2. Add to configuration file

     'components' => [ 'myComponent' => [ 'class'=>'app\components\MyComponent' ], //other components ] 

    and don't forget about 'bootstrap' => ['log','myComponent']

№2:

Inherit method in controller

 public function beforeAction($event) { // ваш код return parent::beforeAction($event); } 

Number 3:

  1. Create behavior: http://www.yiiframework.com/doc-2.0/guide-concept-behaviors.html , see how

  2. Add written behavior to the controller, such as AccessControl