Phalcon PHP: Modify a request URL before it gets dispatched

孤者浪人 提交于 2020-01-14 01:38:09

问题


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:


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


来源:https://stackoverflow.com/questions/27378436/phalcon-php-modify-a-request-url-before-it-gets-dispatched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!