www.example.com/home
变成 www.example.com/inicio
www.example.com/profile
变成 www.example.com/perfil
www.example.com/help
变成 www.example.com/ayuda
等等。我的问题是:在PHP应用程序中支持这种结构的最佳方法是什么?对于传入的请求,我认为在我的router.php
文件中使用以下类似字典的方式就足够了:
<?php
$request = explode("/", trim($_SERVER['REQUEST_URI'], "/"));
// Dictionaries of page slugs.
$slugs = array(
'es' => array(
'inicio' => 'home',
'perfil' => 'profile',
'ayuda' => 'help',
)
// additional languages can be added here
);
// Rewrite any incoming (foreign) requests
if ($host=="www.example.es") { // to be made programmatic
$lang = "es"; // pick up from locale constant rather being hard-coded
if (array_key_exists($request[0], $slugs[$lang])) {
$request[0] = $slugs[$lang][$request[0]];
}
}
...
这基本上是将URL段与其英文对应项进行匹配。如果没有找到,则会正常执行,并且很可能会因为URL段的控制器不存在而导致404错误。
虽然如此,我也希望它具备向后兼容性。例如,在我的应用程序中构建URL时。
目前应用程序只支持英语,因此这些内容都是硬编码的。所以说,当获取一个User
对象时,我会执行以下操作:
<?php
class User {
function __construct($id) {
// fetch user details
$this->profile_url = ROOT . "/profile/" . $this->username;
}
}
什么是最佳方法来替换硬编码的
"/profile/"
,以获取翻译版本,例如在西班牙网站中使用"/perfil/"
?
getUrl()
)的完整对象,这些方法可能是区域设置感知的。 - Wrikken