Aug 30, 2012

CodeIgniter: Dynamically setting the website's language

I have been writing up my own View subsystem for CodeIgniter that seperates the  View more clearly from the controller. I have also designed it with Language support in mind, but for that I had to do some minor edits to the default Language class.

Even though you can load a specific language file in another language, the system will load error messages in the default language. This led to some cases where system errors would be in English, but the site language was something else.

With my new system I can have my default site language can be dynamically set by a user cookie… see the following code:

$lang_temp = $this->input->cookie('language');
if ( $lang_temp )
{
     // NOTE: getDefault() is one of my core Lang.php modifications
     if (!($lang_temp === $this->lang->getDefault()))
     {
        // NOTE: setDefault() is one of my core Lang.php modifications
        $this->lang->setDefault($lang_temp);
     }
} else {
     // Set a cookie with system default
     $this->input->set_cookie('language', $this->lang->getDefault(), '7200', '.' . $_SERVER['HTTP_HOST'], '/', NULL, FALSE);
}
 
But to make the above code work I had to make some changes to the core:



<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/

// ------------------------------------------------------------------------

/**
* Language Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Language
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/language.html
*/
class CI_Lang {

/**
* List of translations
*
* @var array
*/
var $language = array();
/**
* List of loaded language files
*
* @var array
*/
var $is_loaded = array();

/**
* Default language
*
* @var array
*/
var $default_lang;

/**
* Constructor
*
* @access public
*/
function __construct()
{
    $config =& get_config();
    $this->default_lang = ( ! isset($config['language'])) ? 'en' : $config['language'];

    log_message('debug', "Language Class Initialized");
}

// --------------------------------------------------------------------

/**
* Load a language file
*
* @access public
* @param mixed the name of the language file to be loaded. Can be an array
* @param string the language (english, etc.)
* @param bool return loaded array of translations
* @param bool add suffix to $langfile
* @param string alternative path to look for language file
* @return mixed
*/
function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '')
{
    $langfile = str_replace('.php', '', $langfile);

    if ($add_suffix == TRUE)
    {
       $langfile = str_replace('_lang.', '', $langfile).'_lang';
    }

    $langfile .= '.php';

    if (in_array($langfile, $this->is_loaded, TRUE))
    {
       return;
    }

    if ($idiom == '')
    {
       $idiom = ($this->default_lang == '') ? 'en' : $this->default_lang;
    }

    // Determine where the language file is and load it
    if ($alt_path != '' && file_exists($alt_path.'language/'.$idiom.'/'.$langfile))
    {
       include($alt_path.'language/'.$idiom.'/'.$langfile);
    }
    else
    {
       $found = FALSE;

       foreach (get_instance()->load->get_package_paths(TRUE) as $package_path)
       {
          if (file_exists($package_path.'language/'.$idiom.'/'.$langfile))
          {
              include($package_path.'language/'.$idiom.'/'.$langfile);
              $found = TRUE;
              break;
          }
      }

      if ($found !== TRUE)
      {
         show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile);
      }
   }


    if ( ! isset($lang))
   {
      log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile);
      return;
   }

   if ($return == TRUE)
   {
      return $lang;
   }

   $this->is_loaded[] = $langfile;
   $this->language = array_merge($this->language, $lang);
   unset($lang);

   log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile);
   return TRUE;
}

// --------------------------------------------------------------------

/**
* Fetch a single line of text from the language array
*
* @access public
* @param string $line the language line
* @return string
*/
function line($line = '')
{
   $value = ($line == '' OR ! isset($this->language[$line])) ? FALSE : $this->language[$line];

   // Because killer robots like unicorns!
   if ($value === FALSE)
   {
      log_message('error', 'Could not find the language line "'.$line.'"');
   }

   return $value;
}

/**
* Fetch Default language
*
* @access public
* @param void
* @return string Default language code
*/
function getDefault()
{
   return $this->default_lang;
}

/**
* Set Default language
*
* @access public
* @param string The default language
* @return void
*/
function setDefault($language)
{
   $this->default_lang = $language;
}

}
// END Language Class

/* End of file Lang.php */
/* Location: ./system/core/Lang.php */

I am sure you can find other uses for this code.....

My other posts on CodeIgniter include:

2 comments:

  1. kita juga punya nih jurnal mengenai Code Igniter, silahkan dikunjungi dan dibaca , berikut linknya
    http://repository.gunadarma.ac.id/bitstream/123456789/1204/1/50407479.pdf
    semoga bermanfaat ya :)

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!