模块路由不对

I'm experiencing something really strange with the routing of my app, which is an API. I am not using micro, just using the regular Phalcon stack.

Here's my router definition:

$di->set('router', function () {
    $router = new Router(false);

    $router->setDefaultAction('index');
    $router->setDefaultController('index');

    $router->add('/:module/:controller/:params', array(
        'module' => 1,
        'controller' => 2,
        'params' => 3
    ));

    $router->removeExtraSlashes(true);

    return $router;
});

The router works with these example paths:

  • /v1/users/
  • /v1/users/1/
  • /v1/users/1/permissions/

But for some reason the following doesn't match to any route!

  • /v1/

Oddly enough, I was playing around with the route definitions, and, when I change the first param of add to just '/:module' (instead of '/:module/:controller/:params'), the router works as expected!

I am at my wits end, and was hoping someone could help me out. I have no clue what I am doing wrong. Not sure why one route definition would work, while the other would fail. Am I missing something?

Notes:

  • I do not have setDefaultModule because I want the app to throw an error when the module is missing. I plan on versioning the app, and I figured this way I could properly handle missing modules. I couldn't really find any better answers as to how to handle that properly, so I'm doing what I can.
  • I am using the full Phalcon app, instead of the micro, as I want access to the whole framework. Just an architectural decision.

along with your existing route for the module you could also add route for accessing only by module name: as

...
$router->add('/:module/:controller',
    array(
        'module' => 1,
        'controller' => 2,
        'action' => 'index',
    )
);
$router->add('/:module',
    array(
        'module' => 1,
        'controller' => 'index',
        'action' => 'index',
    )
);
...

If you want to version modules and have some order this is one way.

$router = new Router(false);
$versionedModules = ['a', 'b', 'c'];

foreach ($versionedModules as $module) {
    $namespace = 'App\\'. ucfirst($module) . '\Controllers';
    $moduleRouter = new \Phalcon\Mvc\Router\Group([
        'namespace' => $namespace,
        'module' => $module
    ]);

    $moduleRouter->add("/{$module}/:controller/:params/", [
        'controller' => 1,
        'params' => 2
    ]);
}

$router->mount($moduleRouter);