Skip to content

CI Language Extended

Erkan Çakmak edited this page May 3, 2013 · 7 revisions

Category:Core | Category:Core::Community | Category:Core::Language

I am using a lot the Language library and realized that it needs some improvements to be more effecient. So I have done some modifications to it by extending the CI_Language library and overloading the CI_Language::line() method. I have added two more features to it:

  1. echo a "language string" (key) when it isn't exists rather than echoing null so we can realize which lang strings hasn't translated yet e.g:
//when we use the following line of code
echo $this->lang->line("lang_string_key"); 

//we should get 
//NORMAL OUTPUT: false
//but  
//MODIFIED OUTPUT: !-- lang_string_key --!

2)Many times i wanted to pass some variables into some translated lines. So i have added a second optional variable that pass a value or an array to be inserted inside the translated line

e.g:

//in some language file we add a line as the one that follows
$lang['some_line'] = "Hello $1, do you want some $2?";

//when we want to get the translation we can add the following code
echo $this->lang->line('some_line', array('George', 'tea'));

//the output should be: "Hello George, do you want some tea?";

The actual library is the following:

class MY_Language extends CI_Language{

    function line($line, $params=null){

        $return = parent::line($line);
            
        if($return === false){
            return "!-- $line --!";
        }else{
            if (!is_null($params)){
                $return = $this->_ni_line($return, $params); 
            }
            return $return;
        }

    }
    
    private function _ni_line($str, $params){
        $return = $str;
        
        $params = is_array($params) ? $params : array($params);   
        
        $search = array();
        $cnt = 0;
        foreach($params as $param){
            $search[$cnt] = '/\\$'.($cnt + 1).'/';
            $cnt++;
        }

        $return = preg_replace($search, $params, $return);
        
        return $return;
    }
}
Clone this wiki locally