We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

More to Router Groups and Collections

Hey,

I want to have a group/collection to /api and then under that don't specify a controller as a route pattern could go to any controller action.

I am looking for this (Laravel 5 example):

https://github.com/gothinkster/laravel-realworld-example-app/blob/aac8f2c71a81bd14e3be0d63fadd5d3071d7df64/routes/api.php

$usersCollection->setHandler("\App\Controllers\Api\UsersController", true); seems too specific for example.

What if you want more than just a usersCollection?

Anyway of achieving this?

Yes, use group classes.

Yes, use group classes.

Give me an example of how you'd achieve that in router group? Everything I have seen requires you to specify a single controller I want a group of route that could go to different controller and actions like my linked Laravel example.

I am not sure the router (see: cphalcon/issues/12827) can be used in such a way so I am looking for a hack of some sort for now.



145.0k
Accepted
answer
edited May '17

Example:

class YourRoutes extend Phalcon\Mvc\Router\Group
{
    public functio initialize()
    {
        $this->setPaths(['namespace' => 'ControllerNamespace']);
        $this->addGet('/action1', ['controller' => 'controller1', 'action' => 'action1']); // this will be controller1 class
        $this->addGet('/action2', ['controller' => 'controller2', 'action' => 'action2']); // this will be controller2 class
    }
}

and then:

$router->mount(new YourRoutes());

No need for any hacks, this is already implenetend in phalcon in nice and clean way. If you want whole group to be used only by one controller just move "controller" => "controller1"to setPaths and leave only"action" => "action1"` in addGet etc.