I’m trying to update our modules to be id-agnostic, which basically means replacing Yii::$app->getModule('moduleName') with ModuleClass::getInstance(). I found out this sometimes doesn’t work, I mean at some stages of the application, the getInstance() call returns null.
I thought it was safe to use getInstance(), I haven’t been able to figure out which condition causes the empty return value…
Not sure, but it sounds like what you have to do. Another meaning could be request due to URL access to the module. You can test and let us know which is which. In first case, I would do a boostrap file and call the gestInstance() there
Well, we have to return to the same old Definitive Guide in which almost all questions are answered.
Note that you do not want to manually create a new instance of the module class because it will be different from the one created by Yii in response to a request.
Some modules may need to be run for every request. The yii\debug\Module module is such an example. To do so, list the IDs of such modules in the bootstrap property of the application.
No module will be instantiated without explicitly requested by the current URL route. For example, a module named “blog” will be instanticated by Yii framework only when you’ve called “https://example.com/blog/post” or something like that.
You can instantiate a module for every request, as the guide says, but usually you don’t want to do it for performance sake.
I was looking for some way to access the module instance from a widget without using the ID, which I don’t want to be hardcoded. In the Modules section the guide says it’s better not to access modules with fixed ID, and that’s what I’m trying to do, but doesn’t provide alternatives. I found this old discussion exactly on this matter, and in the end there’s no official solution.
The only proper way seems to do what Kartik does, which is allow the developer to provide the module ID in widget config.
Otherwise, one has to traverse all the configured module instances to find the ID by class name. As long as it’s not expected to have more than one module configured.