I have done this for a project.
namespace Myns;
use \Phalcon\Mvc\Micro\Collection;
//Overrides collection methods in order to inject namespace and baseUri
class MicroCollection extends Collection
{
private $_config;
/**
* Inject current namespace and normally proceed further treatment of request to a parent method
* @param null $handler
* @param bool $lazy
* @return mixed
* Default zephir signature:
* public function setHandler(var handler, boolean lazy = false) -> <Collection>
*/
function setHandler($handler = null, $lazy = true)
{
return parent::{__FUNCTION__}(__NAMESPACE__ . '\\' . $handler, $lazy);
}
/**
* @param null $prefix
* @return mixed
* Default zephir signature:
* public function setPrefix(string! prefix) -> <Collection>
*/
function setPrefix($prefix = null){
//inject baseUri to every route prefix
return parent::{__FUNCTION__}($this->_config->application->baseUri . $prefix);
}
/**
* @param null $routePattern
* @param null $handler
* @param null $name
* @return mixed
*
* Default zephir signature:
* public function get(string! routePattern, handler, var name = null) -> <Collection>
*/
function get($routePattern = null, $handler = null, $name = null){
//auto prepend baseUri if route prefix is not set
!self::getPrefix() && $routePattern = $this->_config->application->baseUri . $routePattern;
return parent::{__FUNCTION__}($routePattern, $handler, $name);
}
/**
* @param null $routePattern
* @param null $handler
* @param null $name
* @return mixed
*
* Default zephir signature:
* public function post(string! routePattern, handler, var name = null) -> <Collection>
*/
function post($routePattern = null, $handler = null, $name = null){
//auto prepend baseUri if route prefix is not set
!self::getPrefix() && $routePattern = $this->_config->application->baseUri . $routePattern;
return parent::{__FUNCTION__}($routePattern, $handler, $name);
}
/**
* MicroCollection constructor.
*
* @param \Phalcon\DiInterface|null $di
*/
final function __construct(\Phalcon\DiInterface $di = null){
//resolve config object into local scope
$this->_config = $di->getShared('config');
}
/**
* @param string|null $routePattern
* @param string|null $handler
* @param string|null $name
* @return bool
* This method creates both GET and POST routes automatically
*/
final function via(string $routePattern = null, string $handler = null, string $name = null){
self::get($routePattern, $handler, $name);
self::post($routePattern, $handler, $name);
return true;
}
You basically only need the very last method (via
).
Only change self to parent:
parent::get($routePattern, $handler, $name);
parent::post($routePattern, $handler, $name);
Usage:
$authModule = new MicroCollection(self::getDI()); //I need DI for config object etc, you might not need it...
$authModule->setHandler('AuthModule');
$authModule->via('/login', 'customerLogin', 'customer_login_module'); //This method creates both GET and POST routes automatically