What I want to do: Register a component to an event raised by a controller.
In my config main.php:
'preload' => array(MessageConsumer) // actually an impl class of interface
In my MessageConsumer impl
public function init() {
Yii::app()->getController()->onMessageReceived = array($this, 'onMessageReceived');
}
Expected result: when the init method fires the consumer is registered to the current controller.
Actual result: there's no current controller yet. It seems the pre-load is performed before the webapplication does the controller magic.
So I tried something like:
In my MessageConsumer impl:
public function init() {
$self = $this;
Yii::app()->onBeginRequest(function() use ($self) {
$controller = Yii::app()->getController();
if($controller instanceof MessagingController) {
Yii::app()->getController()->onMessageReceived = array($self, 'onMessageReceived');
}
});
}
Which doesn't work either because it seems the init() is called after the onBeginRequest() event is raised by the webapp.
Is there a way to register to events raised by a controller without explicitly linking the component to the controller class? Obviously I could register the listener in the constructor of the controller but I want to loosely couple the 2 components by using configuration.
Maybe there's some event like "onComponentLoaded" for which I could register? Since a Controller is a component I'd expect the Yii core to fire the event whenever there's a component loaded if there's such an event at all.