Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to achieve multilingual URLs?
    text
    copied!<p>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:</p> <p><code>www.example.com/home</code> becomes <code>www.example.com/inicio</code></p> <p><code>www.example.com/profile</code> becomes <code>www.example.com/perfil</code></p> <p><code>www.example.com/help</code> becomes <code>www.example.com/ayuda</code></p> <p>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 <code>router.php</code> file would suffice:</p> <pre><code>&lt;?php $request = explode("/", trim($_SERVER['REQUEST_URI'], "/")); // Dictionaries of page slugs. $slugs = array( 'es' =&gt; array( 'inicio' =&gt; 'home', 'perfil' =&gt; 'profile', 'ayuda' =&gt; '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]]; } } ... </code></pre> <p>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.</p> <p>Although this words, I need it to be backwards-compatible too. For example, when building URLs in my application.</p> <p>Naturally, as the application is only English at the moment these are just hard-coded. So say, when fetching a <code>User</code> object I do the following:</p> <pre><code>&lt;?php class User { function __construct($id) { // fetch user details $this-&gt;profile_url = ROOT . "/profile/" . $this-&gt;username; } } </code></pre> <p>What is the best method to then replace instances of <code>"/profile/"</code> being hard-coded to getting the translated version, i.e. <code>"/perfil/"</code> in the Spanish site?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload