temuri
temuri

Reputation: 2807

Phalcon routing - making route segments optional

I have the following route added to Phalcon\MVC\Router:

$router = new Phalcon\Mvc\Router();

$router->removeExtraSlashes(true)
    ->setDefaultNamespace('My\Controllers')
    ->setDefaultModule('default')
    ->setDefaultController('index')
    ->setDefaultAction('index');

$router->add('/admin/:controller/:action/:params', [
    'module' => 'admin',
    'controller' => 1,
    'action' => 2,
    'params' => 3,
    'namespace' => 'My\Admin\Controllers'
])->setName('admin_module');

I'm handling the following URLs:

  1. /admin/foo/bar/baz - works good. I get admin module, foo controller, bar action, "baz" parameter.

  2. /admin/foo/bar - works good. I get admin module, foo controller, bar action.

  3. /admin/foo - does not match. I expect to get admin module, foo controller, index action.

  4. /admin - does not match. I expect to get admin module, index controller, index action.

The question:

How can I make route segments optional and default to provided default values of controller and action name. I would like to avoid defining extra routes for /admin and /admin/:controller.

Thank you.

Upvotes: 3

Views: 5189

Answers (1)

lazycommit
lazycommit

Reputation: 414

Most common way to make this works is to add each pattern to Router as custom Route with same paths options (the second argument in Route::add()). As for annotation routes its good to choose few @Route directives for Action methods. This way is majored for usage cause convenient URL generation by Route (route name) will be faster then universal one.

regards

Upvotes: 2

Related Questions