phpyii2yii-modules

Yii2: $loadedModules does not show all modules


Created module "forum" - exactly as written here. Then created nested module "admin":

//"Module.php" in '@app/modules/forum'
namespace app\modules\forum;

class Module extends \yii\base\Module {
    public function init() {
        parent::init();
        \Yii::configure($this, require(__DIR__ . '/config.php'));

        $this->modules = [
            'admin' => [
                // here is my nested module
                'class' => 'app\modules\forum\modules\admin\Module',
            ],
        ];
    }
}

Also created a non-nested module "games" (in the same way) and wrote in "web.php" (main config-file):

'modules' => [
    'forum' => [
        'class' => 'app\modules\forum\Module',
    ],
    'games' => [
        'class' => 'app\modules\games\Module',
    ],
    'admin' => [
        'class' => 'app\modules\forum\modules\admin\Module',
    ],
],

But when I tried to output:

// codeline is written in application view, not in module view
var_dump(array_keys(\Yii::$app->loadedModules));

I saw only these modules:

array(4) {
  string(19) "yii\web\Application"
  string(16) "yii\debug\Module"
  string(14) "yii\gii\Module"
  string(24) "app\modules\forum\Module"

}

"Games" and nested "admin" modules are absent! Although doc says:

$loadedModules property keeps a list of loaded modules, including both direct children and nested ones, indexed by their class names.

But I could get only "forum" myself-created module. What am I understanding wrong?


Solution

  • As documentation says:

    $loadedModules property keeps a list of loaded modules

    which mean that it keeps modules that loaded in current request. E.g. if you are on module's page example.com/forum/ it will contain app\modules\forum\Module but if you on example.com/site where site is controller's name $loadedModules will contain only modules that are set in $bootstrap config property.

    To get list of all modules call Yii::$app->modules. Note that $loadedModules contains app itself since it extends Module class. Yii::$app->modules contains all modules from app config modules property.