phpphalconphalcon-routing

Phalcon router doesn't seem to be set


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?


Solution

  • 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 :)