There is a base class for all modules.

namespace app\components; use Yii; class Module extends \yii\base\Module { public function init() { parent::init(); var_dump(Yii::$app->controller->id); // null :( } } 

All modules expand from it, i.e.

 namespace app\modules\test; class Module extends \app\components\Module { // } 

How can I get the name of the current controller in the base class of the module?

 Yii::$app->controller->id 

returns null

    2 answers 2

    Well for a start not

     Yii::$app->controller->id 

    but

     Yii::app()->controller->id 

    Then he will give you the name of the controller.

    // UPD

    You call it from the init () module . What can this call give you if it doesn't mean which controller you have now. He will always show you NULL!

    and if the question sounds that way

    How can I get the name of the current controller in the base class of the module?

    That answer in any way. because the module does not know anything about the controller to give out some information.

    • 2
      Well, for starters, not Yii::$app->controller->id and Yii::app()->controller->id Then he will give you the name of the controller. Yii::app()->controller->id this is for the first Yii - Guest

    I think the simplest solution would be to create another class from which all the others will be inherited, in which you can do operations with controllers id.

     class MainController extends yii\base\Controller { // some... public function beforeAction($event) { $ct = $event->controller->id; // current ctrl return parent::beforeAction($event); } } 

    And to inherit from it all the other controllers

    class PostController extends MainController { // do something... }

    • you did not quite understand what I mean, corrected the question - Guest