I am trying to register an event from within a module. So, I added this couple of lines in the init function of my module class (protected/modules/points/PointsModule.php
).
class PointsModule extends CWebModule {
public function init() {
...
// Attach the "User Register" event
Yii::app()->user->onUserRegister = array($this, "addPointsForRegistration");
die('init');
}
...
}
I only see the result of the die('init')
when I use the module controller. Any other page of my application won't do anything.
I import the file in config/main.php
file
'import'=>array(
'application.modules.points.*',
),
I don't understand what I am doing wrong here. The file seems to be not loaded at all if I am not using the module's controller.
Is there a way to load a module class (or another component) at each page load in yii? Is there a cleaner way to register an event from inside a module?
Module instance is created only if you use this particular module, same applies to init
method. So, when you access different module event is not attached, even more, other modules are not aware of this, because they have no information that anything global should be registered.
But you use user
component - which is guaranteed to run. You could register event onUserRegister (in user
component) to call some method, prefably not from module, but from something lighter, maybe some Points
model? Of course this breaks modularity, because if you remove PointsModule
it will break user
component.
Maybe you could attach it in config i'm using following config for application component:
'onBeginRequest' => function()
{
YII_DEBUG? : ob_start("ob_gzhandler");
}
Something like:
'user' => [
'onUserRegister' => function()
{
// Handle event here
}
]
Side note: Cross module or more generally cross component interaction migth be tricky. I'm developing extension for this purpose, idea is to aggregate events from whole application and fire them when needed.