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

Why are the order of routes being processed in reverse order?

Let's say we have 2 routes defined like this:

$this->app->get('/user/search', self::foo($app));
$this->app->get('/user/{id}', self::bar($app));

I would have expected /user/search to be matched against before /user/{id}. However, it's the reverse order.

In the documentation, I noticed the following:

Since you can add many routes as you need using the add() method, the order in which routes are added indicate their relevance, latest routes added have more relevance than first added. Internally, all defined routes are traversed in reverse order until Phalcon\Mvc\Router finds the one that matches the given URI and processes it, while ignoring the rest.

Documenting routes in this fashion seems counterintuitive. Every framework I've ever used has parsed routes top/down, which is also the way in which we read code. I'm curious what the technical reason behind this decision was. I'm also curious if the Phalcon team is open to exposing an optional way to set the preferred route priority to be top/down versus bottom/up.

Any feedback would be appreciated.

Hi, have you tried using patterns?


<?php

$router->add(
    "/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params",
    [
        "controller" => "posts",
        "action"     => "show",
        "year"       => 1, // ([0-9]{4})
        "month"      => 2, // ([0-9]{2})
        "day"        => 3, // ([0-9]{2})
        "params"     => 4, // :params
    ]
);

Here's doc

I guess we can just add some global option to configure way of route orders.

I guess we can just add some global option to configure way of route orders.

That would be great. I started looking at porting a large app from fastroute to phalcon router and reordering the routes is a lot of work. It would be nice to set a flag on the router to match top to bottom like most other routers.

edited Apr '17

Thanks for the response @PolDeveloper, but my example was more to demonstrate a route order collision and that it's misleading to be bottom up, instead of top down. I was similarly migrating a site to phalcon that had over 300 routes. It's unrealistic to just create a generic route pattern that satisfies all preexisting routes.

I agree with the proposed solution by Wojciech.