I'm developing a niche social networking site that is going multilingual. That means our current URL structure will soon need to start using translated words for slugs like the following:
www.example.com/home
becomes www.example.com/inicio
www.example.com/profile
becomes www.example.com/perfil
www.example.com/help
becomes www.example.com/ayuda
And so on. My question is: what's the best way to support this in a PHP application? For incoming requests, I thought a dictionary like the following in my router.php
file would suffice:
<?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]];
}
}
...
Which basically takes URL segments and matches them against an English counter-part if it exists. If not, then it will proceed as normal and most likely cause a 404 as a controller doesn't exist for URL segment.
Although this words, I need it to be backwards-compatible too. For example, when building URLs in my application.
Naturally, as the application is only English at the moment these are just hard-coded. So say, when fetching a User
object I do the following:
<?php
class User {
function __construct($id) {
// fetch user details
$this->profile_url = ROOT . "/profile/" . $this->username;
}
}
What is the best method to then replace instances of "/profile/"
being hard-coded to getting the translated version, i.e. "/perfil/"
in the Spanish site?