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

Routing group REST API

Hello,

I am currently developing a REST API with Phalcon and i have a doubt about group routing. So my project now is like :

$app = new Phalcon\Mvc\Micro();

$app->get('/products', function () {
    //anything
});

$app->get('/products/{id}', function ($id) {
    //anythingelse
});

$app->handle();

To avoid repeting /products, i red about group and i don't quite figured out the true meaning and i want to do something like :

 $app->group('/products', function() use($app) {
  this->requestProducts($app);
 });

function requestProducts($app)
{
$app->get('/', function () {
    //something
 });

 $app->get('/id/:id/', function ($id) {
    //other stuff
 });   
}

Can anyone help me around here?

Best regards.



2.1k

I believe the function you are looking for is collection.

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Micro_Collection.html

what you want to do is.

class ProductController extends \Phalcon\Mvc\Controller { public function indexAction() { //handles with/without id } }

$app = new Phalcon\Mvc\Micro(); $collection = new Phalcon\Mvc\Micro\Collection(); $collection->setHandler(new ProductController()); $collection->get('/product/{id}', 'index'); $app->mount($collection);