I’m creating a module and I’ve written a web application component class that I access from the controllers in my module by calling $this->component, which I set in the controller’s init()-function.
Now I’m wondering what would be the correct way to initialize and access the module component through the module.
The only solution I came up with was to create a public variable in the module for the component and initialize it using new and by calling it’s own init()-function in the modules init()-function as shown below:
class ExampleModule extends CWebModule
{
public $component;
...
public function init()
{
...
$this->component = new Component();
$this->component->init();
}
...
}
NOTE: The class- and variable names as just examples.
When using this solution I can access the module component by calling:
Yii::app()->getModule('example')->component
There must be a better way to do this that I haven’t thought of…
class MyModule extends CWebModule
{
public function init()
{
$this->setImport(array(
'my.models.*',
'my.components.*', // FooComponent.php is located there.
));
$this->setComponent('foo', new FooComponent);
}
}
One thing I noticed was that if you configure parameters for your component they won’t be accessible in the components init()-function. But this is probably as it was intended.