Codeigniter urls in multiple languages but handled by the same controller
-
25-10-2019 - |
Question
Let's say I would like to list products on a codeigniter project and support multiple languages, so that someone would select english and get the url example.com/products/5
where 5 is the page number, and someone else would select italian and go get example.com/prodotti/5
. Behind the scenes, I want to have a controller that gets passed a language parameter and a page number parameter to handle these requests. I have a small number of situations like this, and I was thinking about creating two controllers named products and prodotti and then calling a third controller from each one of them by giving it the parameters that it needs.
Is there a better way? Is this achievable with routes?
Solution
Here's how I've solved it:
application/config/routes.php
$route['products/(.*)'] = 'products/en/$1';
$route['prodotti/(.*)'] = 'products/it/$1';
application/controllers/products.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Products extends CI_Controller {
public function index($lang, $nr)
{
echo 'lang: ', $lang, ' nr: ',$nr;
}
// https://gist.github.com/1096571
function _remap($method)
{
$param_offset = 2;
if ( ! method_exists($this, $method))
{
$param_offset = 1;
$method = 'index';
}
$params = array_slice($this->uri->rsegment_array(), $param_offset);
call_user_func_array(array($this, $method), $params);
}
}