I'm new with Phalcon. I just wanted to know if is this possible to define routes inside each modules separately?
|
Mar '14 |
2 |
834 |
0 |
I meant is this the best way? Or can tell me if you have you have better idea?
services.php
...
$di['router'] = function () {
$router = new Router();
$router->setDefaultModule("frontend");
$router->setDefaultNamespace("Sample\Frontend\Controllers");
$modules = scandir(__DIR__ . '/../apps/');
foreach ($modules as $module) {
if (file_exists(__DIR__ . '/../apps/' . $module . '/config/routes.php')) {
include __DIR__ . '/../apps/' . $module . '/config/routes.php';
}
}
return $router;
};
...
routes.php
...
$router->add(
"/index",
[
'namespace' => 'Sample\Backend\Controllers',
'module' => 'backend',
'controller' => 'index',
'action' => 'index',
]
);
...
A router must know in advance all routes in the application, so it can forward to the right module.
Regarding application organization, your approach is a good option.
I use this method: in my application bootstrap:
<?php
// Routing
$router = new Phalcon\Mvc\Router(false);
$router->setDefaultModule('site');
$router->setDefaultController('index');
$router->setDefaultAction('index');
// Default router
$router->add('/:module/:controller/:action/:params', array(
'module' => 1,
'controller' => 2,
'action' => 3,
'params' => 4
));
foreach ($application->getModules() as $module) {
$routesClassName = str_replace('Module', 'Routes', $module['className']);
if (class_exists($routesClassName)) {
$routesClass = new $routesClassName();
$router = $routesClass->add($router);
}
}
$router->removeExtraSlashes(true);
$di->set('router', $router);
in my module directory (eg. Backend module): "backend/Routers.php"
<?php
namespace Backend;
class Routes
{
public function add($router)
{
$backend = new \Phalcon\Mvc\Router\Group(array(
'module' => 'backend',
'controller' => 'index',
'action' => 'index'
));
$backend->setPrefix('/backend');
$router->add('/backend(/:controller(/:action(/:params)?)?)?', array(
'module' => 'backend',
'controller' => 2,
'action' => 4,
'params' => 6,
))->setName('backend');
$backend->add('/', array(
'action' => 'index',
))->setName('backendhome');
$router->mount($backend);
return $router;
}
}