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

Sort route after add.

All Routes added as annotations. Is it possible to change the order after adding?

Something like that:

<?php 
$manager->attach('router:beforeCheckRoutes', function (\Phalcon\Mvc\Router\Annotations $router) {
      $namedPage = $router->getRouteByName('Front:Abc:NamedPage');
      $router->add($namedPage, \Phalcon\Mvc\Router::POSITION_LAST);
    });
?>


79.0k
Accepted
answer

I did something similar, but on the same class where routes are defined. I maintain route ID's after adding, and looping through them to set some special routes which are later handled by the app.

In your case, I guess it's not that simple, but you can also loop through all the routes and to re-arrange them.



2.4k

Solution looks something like this:

<?php namespace fastPanel\Mvc;

use Phalcon\Mvc\Router\Annotations;

/**
 * Class Router
 *
 * Expansion of standard class annotations router.
 *
 * @package fastPanel\Mvc
 * @version 1.0.0
 */
class Router extends Annotations {

  /**
   * Set all routes.
   *
   * @param array $routes
   */
  public function setRoutes(array $routes) {
    $this->_routes = $routes;
  }

}

/* End of file Router.php */
/* Reordering routes. */
    $manager->attach('router:beforeCheckRoutes', function ($event, \fastPanel\Mvc\Router $router) {
      /* Route list to move. */
      $moveRoutes = [
        'Front:Abc:NamedPage:Locale',
        'Front:Abc:NamedPage'
      ];

      foreach ($moveRoutes as $route) {
        /* Find target route. */
        $namedRoute = $router->getRouteByName($route);

        if ($namedRoute) {
          /* Get all routes. */
          $routes = $router->getRoutes();

          /* Move target route. */
          \fastPanel\Helpers\Arrays::moveAsFirst($routes, $namedRoute->getRouteId());

          /* Set routes in new orders. */
          $router->setRoutes($routes);
        }
      }
    });