My universal router:
CREATE TABLE IF NOT EXISTS `router` (
`id` int(10) unsigned NOT NULL,
`uri` varchar(255) COLLATE utf8_general_mysql500_ci NOT NULL,
`uri_index` smallint(5) unsigned NOT NULL,
`module` varchar(32) COLLATE utf8_general_mysql500_ci NOT NULL,
`controller` varchar(32) COLLATE utf8_general_mysql500_ci NOT NULL,
`action` varchar(32) COLLATE utf8_general_mysql500_ci DEFAULT NULL,
`params` text COLLATE utf8_general_mysql500_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_mysql500_ci;
ALTER TABLE `router`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `uri` (`uri`,`uri_index`);
class Router extends \Phalcon\Mvc\Model
{
public static function setRouter($di)
{
$config = $di->getConfig()->router;
$di->set('router', function () use ($config)
{
$router = new \Phalcon\Mvc\Router();
$router->clear();
$router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
$router->setDefaultModule($config->defaultModule);
preg_match('~/*([\w\d-_]+)~iu', $router->getRewriteUri(), $matches);
if (!empty($matches[1]))
{
list($uri, $uriIndex) = explode('-', $matches[1]);
$route = self::findFirst([
'conditions' => 'uri = ?1 AND uri_index = ?2',
'bind' => [1 => $uri, 2 => (!empty($uriIndex)) ? (int)$uriIndex : 0]
]);
if ($route)
{
$router->add(
$router->getRewriteUri(),
[
'module' => $route->module,
'controller' => $route->controller,
'action' => $route->action,
'params' => unserialize($route->params)
]
);
}
}
$router->add(
"/([a-zA-Z0-9_-]++)",
[
'module' => 1
]
);
$router->add(
"/([a-zA-Z0-9_-]++)/([a-zA-Z0-9\._]++)",
[
'module' => 1,
'controller' => 2
]
);
$router->add(
"/([a-zA-Z0-9_-]++)/([a-zA-Z0-9\._]++)/([a-zA-Z0-9\._]++)",
[
'module' => 1,
'controller' => 2,
'action' => 3
]
);
$router->add(
"/([a-zA-Z0-9_-]++)/([a-zA-Z0-9\._]++)/([a-zA-Z0-9\._]++)(/.*+)?+",
[
'module' => 1,
'controller' => 2,
'action' => 3,
'params' => 4
]
);
return $router;
});
}
}