Hi all,
I'm currently building a new module-based CMS at work using the Phalcon framework. I've ran into a problem which I've managed to solve but I would like to know if I've done it the 'right' way, if there is any. I'll explain:
I started out with
Class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
but I soon discovered this led to code repetition in new modules when it came to registerServices since I'm using namespaces for my modules and it was impossible to pass the namespace as a parameter meaning I'd have to copy the registerServices function for every new module I create.
looked at ModuleDefinitionInterface and noticed it only has two methods, registerAutoloader and registerServices so I've decided to create my own class, ModuleTemplate which implements it's own registerServices with two extra parameters. The reason for this is that the code in registerServices won't change much at all, apart from the namespace so I wanted a template class that I can use to extend new modules with.
I ended up with the code below:
namespace Core;
class ModuleTemplate {
public function registerServices($oDi, $sNameSpace = '', $bCore = true)
{
//Registering a dispatcher
$oDispatcher = new \Phalcon\Mvc\Dispatcher();
//Check if the module's controller has been extended, if not, fall back to the default controller
if(class_exists('\App\\'.$sNameSpace.'\Controllers\\'.$sNameSpace.'Controller') === true) {
$oDispatcher->setDefaultNamespace('\App\\'.$sNameSpace.'\Controllers');
} else {
$oDispatcher->setDefaultNamespace('\App\\'.$sNameSpace.'\Controllers\\'.$this->sFallback);
}
$oDi->set('dispatcher', $oDispatcher);
//Registering the view component
$sNameSpaceLower = strtolower($sNameSpace);
if($bCore === true) {
$dir = __DIR__.'/views/';
} else {
$dir = MODULE_DIR.'/'.$sNameSpaceLower.'/views/';
}
$oView = new \Phalcon\Mvc\View\Simple();
$oView->setViewsDir($dir);
$oView->registerEngines(array(
".volt" => 'Phalcon\Mvc\View\Engine\Volt'
));
$oDi->set('view', $oView);
}
}
The class above is part of the CMS core which is outside of the modules folder and any new module extends this through:
class Module extends \Core\ModuleTemplate {
public function registerServices($oDi, $sNameSpace = '', $bCore = false) {
parent::registerServices($oDi,__NAMESPACE__,false);
}
}
I've tested the code and everything works but since I've only sparred with Phalcon for about two weeks I can't help but wonder if I went about this the right way?