2

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?

Boolean_Type
  • 1,146
  • 3
  • 13
  • 40

1 Answers1

4

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.

Tony
  • 5,797
  • 3
  • 26
  • 22
  • 1
    Thanks! And I noticed, that `$loadedModules` will contain **NOT exactly only** modules that are set in `$bootstrap` config property. If u noticed, in `contact` page I saw also _app\modules\forum\Module_, which is NOT in bootstrap. It's because for purpose of experiment I called `\Yii::$app->getModule('forum');` in `contact` view - thus I **loaded via getModule() method** one more module - `forum`. I added `\Yii::$app->getModule('forum')->getModule('admin');` - `admin` module now is also present in `$loadedModules`! The same situation with `games` module. Unexpected behavior for Yii2-beginner) – Boolean_Type Jul 20 '15 at 22:30
  • Yes, you're right, when you call `\Yii::$app->getModule();` the module will appear in `$loadedModules` – Tony Jul 21 '15 at 03:15