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

How to grab and dump Routes from annotations?

Start loader:

$loader = new \Phalcon\Loader();
$loader->registerNamespaces(
        array(
            'Pl\Controllers' => $config->application->controllersDir,
        )
    )->register();

Set dispatcher w/namespaces:
  $di->set('dispatcher', function() {
    $dispatcher = new Phalcon\Mvc\Dispatcher();
    $dispatcher->setDefaultNamespace('Pl\Controllers');
    return $dispatcher;
  });

Define controller:

<?
namespace Pl\Controllers;
/**
 * @RoutePrefix("/page")
 */
class PageController extends \Phalcon\Mvc\Controller {
    /**
      * @Get("/index", name="pages-index")
      */
    public function indexAction() {
    }

Trying to get routes definitions from controller:
  $di->set('router', function() {
    $router = new \Phalcon\Mvc\Router\Annotations();
    $router->addResource('Pl\Controllers\Page', '/page');
// dump routes
    foreach ($router->getRoutes() as $r) {
        echo $r->getName().'<br />';
      }

Nothing outputs, and no routes added, no errors, router works as default /:contoller/:action

Please help :)



98.9k

Hi, the routes are loaded when the handle method is called in the router, this usually happens in Phalcon\Mvc\Application.

$di['router'] = function() {
    $router = new \Phalcon\Mvc\Router\Annotations(false);
    $router->addResource('Pl\Controllers\Page', '/page');

    //This is only for debugging purposes
    $router->handle('/page');

    // dump routes
    foreach ($router->getRoutes() as $r) {
        echo $r->getName().'<br />';
    }

    return $router;
};


1.2k

Hi Andres! I've started project from a scratch, and copied your sample from a gist: https://gist.github.com/4543132

Followed your code to use Annotations as Routing definitions, but getting error: Fatal error: Phalcon\Mvc\Router\Annotations::handle(): Call to undefined method getmethodannotations() in /var/www/ph09/public/index.php on line 107

I have published generated project in Github: https://github.com/228vit/ph09 If you have some time please look at this. Thank you!



98.9k

Can you try again recompiling 0.9.0? I uploaded a fix for that in recent commits



1.2k
Accepted
answer
edited Oct '14

Wow! With new recompiled Phalcon 0.9.0 everything works :) but if I try to dump routes as you described, I getting error. The right way is dump them after app launched:

  $application = new \Phalcon\Mvc\Application();
  $application->setDI($di);
  echo $application->handle()->getContent();
  //This is only for debugging purposes
  $application->router->handle('/');
  // dump routes
  foreach ($application->router->getRoutes() as $r) {
    echo $r->getName().'<br />';
  }

Thanks for quick response!