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

Call the correct controller from URI

I am using Micro and I don't want to instantiate all the controllers at once so I am using this:

$controller = explode('/', $app->request->getUri());

$collection = new Phalcon\Mvc\Micro\Collection();
$collection->setHandler(ucfirst($controller[1]) . 'Controller', true);
$collection->get('/', 'index');
...
$app->mount($collection);

Is there a way to get just the user from the request URI so I don't have to extract it from a string?

Also, am I doing this the right way?



145.0k
Accepted
answer
instantiate all the controllers at once

But they don't, they instantiated only when need to be.

Yep, I got that completely wrong.

So:

$collections['index'] = new Phalcon\Mvc\Micro\Collection();
$collections['index']->setHandler('IndexController', true);
$collections['index']->get('/', 'index');
...
$collections['users'] = new Phalcon\Mvc\Micro\Collection();
$collections['users']->setHandler('UsersController', true);
$collections['users']->get('/users', 'index');
...

foreach($collections as $collection)
    $app->mount($collection);

Would you say this is a good approach?

edited Jun '16

Yea, i would use it like this. But i would defintely put this to seperated file like collections.php or routes.php.

Yea, i would use it like this. But i would defintely put this to seperated file like collections.php or routes.php.

Yes I used something like this: https://github.com/phalcon/store