Issue with specifying parameter in Router Group

I’ve created a class which extends Phalcon\Mvc\Router\Group and attempted to add the following route:

    $this->add('/latest/{id}', array(
        'action' => 'index',
    ))->setName('talks-latest');

but the following exception is thrown:

PhalconException: Action 'latest' was not found on handler 'talks'

Yet the documentation says that should work. Any ideas?



83.4k

Hello Matthew,

Try this:

<?php

//Disable default routes!!
$router = new \Phalcon\Mvc\Router(false);

//Create a group with a common module and controller
$blog = new \Phalcon\Mvc\Router\Group(array(
    'module' => 'blog',
    'controller' => 'tasks'
));

//Add another route to the group
$blog->add('/latest/{id}', array(
  'action' => 'index',
))->setName('talks-latest');

//Add the group to the router
$router->mount($blog);

$router->handle('/latest/100');

echo $router->getControllerName(), PHP_EOL;
echo $router->getActionName(), PHP_EOL;
print_r($router->getParams()));

Thanks for the feedback. When I add the route, as you've suggested, in public/index.php, it works fine. However, if I try and add it in a class as follows, it doesn't

class TalkRoutes extends Phalcon\Mvc\Router\Group
{
    public function initialize()
    {
        $this->setPaths(array(
            'controller' => 'talks',
        ));

        //All the routes start with /blog
        $this->setPrefix('/talks');

        //Add a route to the group
        $this->add('/latest', array(
            'action' => 'index',
        ))->setName('talks-latest');

        $this->add('/old', array(
            'action' => 'archive'
        ))->setName('talks-archive');
    }
}


83.4k

Try this:

<?php

//Disable default routes
$router = new \Phalcon\Mvc\Router(false);

class TalkRoutes extends Phalcon\Mvc\Router\Group
{
    public function initialize()
    {
        $this->setPaths(array(
            'controller' => 'talks',
        ));

        //All the routes start with /blog
        $this->setPrefix('/talks');

        //Add a route to the group
        $this->add('/latest', array(
            'action' => 'index',
        ))->setName('talks-latest');

        $this->add('/old', array(
            'action' => 'archive'
        ))->setName('talks-archive');
    }
}

//Create a group with a common module and controller
$talk = new TalkRoutes();

//Add the group to the router
$router->mount($talk);

$router->handle('/talks/latest');

echo $router->getControllerName(), PHP_EOL;
echo $router->getActionName(), PHP_EOL;

Thanks. I'll try that out.