[eluser]Phil Sturgeon[/eluser]
Have just finished a hook that does exactly this.
2x CI config variables.
- Supported languages = array('EN' => English, 'FR' => French, etc)
- Default language = 'EN'
1x Hook entry in config/hooks.php
Code:
$hook['pre_controller'] = array(
'function' => 'PickLanguage',
'filename' => 'pick_language.php',
'filepath' => 'hooks',
);
1x Hook file
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
session_start();
function PickLanguage() {
require_once(APPPATH.'/config/languages.php');
// Lang set in URL via ?lang=something
if(!empty($_GET['lang']))
{
// Uppercase and only 2 characters long
$lang = strtoupper(substr($_GET['lang'], 0, 2));
$_SESSION['lang_code'] = $lang;
}
// Lang has already been set and is stored in a session
elseif( !empty($_SESSION['lang_code']) )
{
$lang = $_SESSION['lang_code'];
}
// Still no Lang. Lets try some browser detection then
else
{
$accept_langs = $this->obj->input->server('HTTP_ACCEPT_LANGUAGE');
if (!empty( $accept_langs ))
{
// explode languages into array
$accept_langs = explode(',', $accept_langs);
log_message('debug', 'Checking browser languages: '.implode(', ', $accept_langs));
// Check them all, until we find a match
foreach ($accept_langs as $lang)
{
// Turn en-gb into EN
$lang = strtoupper(substr($lang, 0, 2));
// Check its in the array. If so, break the loop, we have one!
if(in_array($lang, array_keys($config['supported_languages'])))
{
break;
}
}
}
// Still not found a lang, lets just use the default
if(empty($lang))
{
$lang = $config['default_language'];
}
// Whatever we decided the lang was, save it for next time to avoid working it out again
$_SESSION['lang_code'] = $lang;
}
// Check the provided lang is available
if(!in_array($lang, array_keys($config['supported_languages'])))
{
exit('This language doesnt exist boso!');
}
// Load CI config class
$CI_config =& load_class('Config');
// Set the language config. Getting 'English' from the array by calling it from its key of 'EN', and make it lowercase so CI looks for 'english'
$CI_config->set_item('language', $config['supported_languages'][$lang]);
// Sets a constant to use throughout ALL of CI.
define('DEFAULT_LANGUAGE', $lang);
}
?>
Then, you can use DEFAULT_LANGUAGE in all your models and everywhere else in CI to reference your lang specific data. Works beautifully!
Edit - 07/01/09: Added in browser detection support.