Phalcon PHP:在分发请求URL之前,先对其进行修改 [英] Phalcon PHP: Modify a request URL before it gets dispatched

查看:149
本文介绍了Phalcon PHP:在分发请求URL之前,先对其进行修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在发送请求之前修改请求URL的方法.例如,以下网址应由相同的控制器/操作处理:

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

我想捕获国家代码(如果存在的话),然后重写不带该URL的URL,以便控制器不必处理它.我尝试了'dispatch:beforeDispatchLoop'事件,但它并非针对这种情况而设计.

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.

有什么主意吗?

推荐答案

如果您可以约定所有国家(地区)代码都在路径中排在首位,那么也许有一条附加的重写规则可以帮助您:

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>


编辑

如果您确实需要使用PHP进行此操作,建议您尽早拦截国家/地区代码,以免破坏 Phalcon \ Mvc \ Router 使用方法 getRewriteUri 被可以执行任何操作的操作所覆盖,只是返回不带国家/地区代码部分的URI:


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

这篇关于Phalcon PHP:在分发请求URL之前,先对其进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆