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?
I could always be wrong, but here goes...
The standard way to achieve multilingual websites is to use i18n dictionary/template techniques in which you have a separate dictionary for each language, and in some cases different templates.
However, in such cases, I have never seen anybody change the language of their URL's. URL's map a request to files on the server disk (generally speaking), and there for shouldn't change based on language if you can avoid it.
It is common to prefix the 'path' section of your URL with the language you are requesting - ie: http://foo.bar/en-us/foobar.html
To summarize: I wouldn't worry about translating your URLs as it isn't a standard practice (atleast, not that I have seen). Simply prefix the URL 'path' with a language denotation such as in the URL above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With