Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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);
    });
?>


46.5k
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.



1.2k

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);
        }
      }
    });