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.



1.4k

I believe the function you are looking for is collection.

http://docs.phalconphp.com/en/latest/api/Phalcon%5Mvc%5Micro%5Collection.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);