Phalcon PHP: Modify a request URL before it gets dispatched

1.5k views Asked by At

I'm looking for a way to modify a request URL before it gets dispatched. For instance, the following URLs should be handled by the same controller/action:

/en/paris
/de/paris
/paris

I would like to capture the country code if it is present, then rewrite the URL without it so that controllers don't have to deal with it. I tried the 'dispatch:beforeDispatchLoop' event but it doesn't seam to be designed for that.

Any idea?

1

There are 1 answers

2
cvsguimaraes On BEST ANSWER

If you can convention that all country code comes first in the path, perhaps an additional rewrite rule can help you:

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([a-z]{2})/(.*)$ index.php?_lang=$1&_url=/$2 [QSA,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

EDIT

If you really need to do this in PHP, I'd recommend you to intercept the country code at the earliest to not break the default routing behavior (i.e need to write all routes manually). One way to do this is by setting a shared service in your main DI to replace the default 'router' service. The customized router consist simply in a child of Phalcon\Mvc\Router with the method getRewriteUri overridden by something that does whatever you want them just return the URI without the country code part:

namespace MyApp\Services;

use Phalcon\Mvc\Router as PhRouter;

class Router extends PhRouter
{
    public function getRewriteUri()
    {
        $originalUri = parent::getRewriteUri();

        // Now you can:
        // Check if a country code has been sent and extract it
        // Store locale configurations to be used later
        // Remove the country code from the URI

        return $newUri;
    }
}