2016年7月26日 星期二

CodeIgniter套用language備忘

在CI預設FrameWork是沒加上語系表,不過語系表方便多國語言套用~這很好用就Memo一下!!

在language新增相關語系資料夾 etc: en, zh ...

在config
  : autoload
  $autoload['model'] = array('Appconfig', ...

  :config
  $config['language'] = 'zh';

  :hooks
  $hook['post_controller_constructor'] = array(
                                'class'    => '',
                                'function' => 'load_config',
                                'filename' => 'load_config.php',
                                'filepath' => 'hooks'
                                );

在hook
  新增load_config.php

function load_config(){
    $CI =& get_instance();
    foreach( $CI->Appconfig->get_all()->result() as $app_config )
    {
        $CI->config->set_item( $app_config->key, $app_config->value );
    }
    
    //Set language from config database
    //Loads all the language files from the language directory
    
    if ( $CI->config->item( 'language' ) )
    {
        $CI->config->set_item( 'language', $CI->config->item( 'language' ) );
        
        $map = directory_map('./application/language/' . $CI->config->item( 'language' ));

        foreach($map as $file)
        {
            if ( substr(strrchr($file,'.'),1) == "php")
            {
                $CI->lang->load( str_replace( '_lang.php', '', $file ) );    
            }
        }
    }
    
    //Set timezone from config database
    if ( $CI->config->item( 'timezone' ) )
    {
        date_default_timezone_set( $CI->config->item( 'timezone' ) );
    }
    else
    {
        date_default_timezone_set( 'America/New_York' );
    }
}
  
在model
  新增appconfig.php

class Appconfig extends CI_Model {
function exists($key)
{
$this->db->from('app_config');
$this->db->where('app_config.key',$key);
$query = $this->db->get();

return ($query->num_rows()==1);
}

function get_all()
{
$this->db->from('app_config');
$this->db->order_by("key", "asc");
return $this->db->get();
}

function get($key)
{
$query = $this->db->get_where('app_config', array('key' => $key), 1);

if($query->num_rows()==1)
{
return $query->row()->value;
}

return "";

}

function save($key,$value)
{
$config_data=array(
'key'=>$key,
'value'=>$value
);

if (!$this->exists($key))
{
return $this->db->insert('app_config',$config_data);
}

$this->db->where('key', $key);
return $this->db->update('app_config',$config_data);
}

function batch_save($data)
{
$success=true;

//Run these queries as a transaction, we want to make sure we do all or nothing
$this->db->trans_start();
foreach($data as $key=>$value)
{
if(!$this->save($key,$value))
{
$success=false;
break;
}
}

$this->db->trans_complete();
return $success;

}

function delete($key)
{
return $this->db->delete('app_config', array('key' => $key)); 
}

function delete_all()
{
return $this->db->empty_table('app_config'); 
}
}

沒有留言: