1

I have set a custom route, my routes.php currently looks like this:

<?php
$router = new Phalcon\Mvc\Router();

$router->add('athlete/{username}', array(
    'controller' => 'athlete',
    'action' => 'index',
));

return $router;

In my services.php I'm setting the router:

$di->set('router', function() {
    return require __DIR__ . '/routes.php';
});

The index Action of my AthleteController looks like this, for testing purposes I'm passing the param to the view (username):

public function indexAction()
{
    $username = $this->dispatcher->getParam('username');

    if (!isset($username)) {
        $user = Users::findFirstByUsername($this->auth->getIdentity()['username']);
    } else {
        $user = Users::findFirstByUsername($username);
        if (!$user) {
            $this->flash->error('Could not find this user');
        }
    }
    $this->view->user = $user;
    $this->view->username = $username;
    $this->view->setTemplateBefore('public');
}

When I'm not using a custom param, it works, it can find the user and display his username. However, when I'm using for example the url athlete/kerowan, I get the error Action 'kerowan' was not found on handler 'athlete' whicht, to my understanding, means, that the router somehow isn't set correctly or doesn't catch the URL. Any ideas?

Patrick Manser
  • 1,133
  • 2
  • 12
  • 31

2 Answers2

2

Some time ago I had the same problem and I could not find anywhere in the docs or in the forum how to create route with optional params. The best solution I came up with is to have two routes if I want method to have different behaviour (like in your example). This will do the trick for you:

$router->add('/athlete/{username}', 'Athlete::index');
$router->add('/athlete', 'Athlete::index');

If someone has better/more elegant solution please share :)

Nikolay Mihaylov
  • 3,868
  • 8
  • 27
  • 32
  • And again thank you :) Seems odd, because in the Vokuro sample-app it seems to work. But whatever, this did the trick for me! – Patrick Manser Mar 18 '16 at 11:56
1

By default phalcon's router is using auto routing in this convention : '/:module/:controller/:action/:params in multimodule application and '/:controller/:action/:params in single module application. If you want to get rid from it then you have to pass false to router constructor.

Juri
  • 1,369
  • 10
  • 16