Events for the ModuleDefinitionInterface

Hello everyone,

since two days I have worked and tested the events. The general usage is more or less clear. But now I have a MVC application implemented with the ModuleDefinitionInterface. I decided to use an extended version of this interface and named it ModuleDefinitionAbstract. This works like:

abstract class ModuleDefinitionAbstract implements Phalcon\Mvc\ModuleDefinitionInterface{
...
}

This class uses standard behaviors like standard registering of auto loaders for the module. I implemented in my modules like:

class Init extends Namespace\ModuleDefinitionAbstract{}

Now I would like to use events for the ModuleDefinitionAbstract. But I don't find any idea to do this. Because I would like to have function like module-based configuration loading etc. as standard event. Currently standardly the registerAutoloaders and the registerServices gets called.

I tried already this:

Listener:

class Listener {

    protected function _initialize(){
    }

    protected function _initConfiguration(){
    }

    protected function _initModuleConfiguration(){
    }

    protected function _initCustomerConfiguration(){
    }
}

and added it to the standard events manager in my bootstrap:

$eventManager = new Phalcon\Events\Manager();
$eventManager->attach('moduleDefinitionAbstract', new Namespace\ModuleDefinitionAbstract\Listener());
$this->getDI()->set('eventsManager', $eventManager);

In the above abstract class I used it like:

abstract class ModuleDefinitionAbstract implements Phalcon\Mvc\ModuleDefinitionInterface{

    ....

    protected function _initConfiguration(){
        echo "init conf";
    }
}


85.4k

I would use just 'module' as prefix for events:

$eventManager = new Phalcon\Events\Manager();
$eventManager->attach('module', new Namespace\ModuleDefinitionAbstract\Listener());
$this->getDI()->set('eventsManager', $eventManager);

Then you need to trigger events where you consider they must be called:

$this->di['eventsManager']->fire('module:_initConfiguration', $this);

I assume the better place for that is the module definition:

<?php

use Phalcon\Loader,
    Phalcon\Mvc\Dispatcher,
    Phalcon\Mvc\View,
    Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{

    public function registerAutoloaders()
    {
    }

    public function registerServices($di)
    {   
        $di['eventsManager']->fire('module:_initConfiguration', $this);
    }

}

The biggest question for me is, is it possible to attach an event listener to the Phalcon\Loader which get fired if for example get loaded "Ns\Class::function()"? Do you know what I mean? Then I could use it easily.



85.4k

Yes, you can add event listeners to Phalcon\Loader, http://docs.phalconphp.com/en/latest/reference/loader.html#autoloading-events, hope that helps

Yes that helps. I will try to overwrite this like I need it.