用户
 找回密码
 入住 CI 中国社区
搜索
查看: 4902|回复: 5
收起左侧

[Others] CI使用session和hooks实现多语言切换以及自动检查浏览器语言

[复制链接]
发表于 2016-1-1 16:46:13 | 显示全部楼层 |阅读模式
我不会说话,直接主题了哈!嘿嘿。使用session实现的
picklanguage.phpapplication/hooks/pickLanguage.php
PHP复制代码
function pickLanguage()
{
        require APPPATH.'/config/language.php';
 
        // Re-populate $_GET
        parse_str($_SERVER['QUERY_STRING'], $_GET);
 
        // If we've been redirected from HTTP to HTTPS on admin, ?session= will be set to maintain language
        if ($_SERVER['SERVER_PORT'] == 443 and ! empty($_GET['session']))
        {
                session_start($_GET['session']);
        }
        else
        {
                //session_start();
        }
 
        // Lang set in URL via ?lang=something
        if ( ! empty($_GET['lang']))
        {
                // Turn en-gb into en
                $lang = strtolower(substr($_GET['lang'], 0, 2));
 
                log_message('debug', 'Set language in URL via GET: '.$lang);
        }
 
        // Lang has already been set and is stored in a session
        elseif ( ! empty($_SESSION['langCode']))
        {
                $lang = $_SESSION['langCode'];
 
                log_message('debug', 'Set language in Session: '.$lang);
        }
 
        // Lang has is picked by a user.
        elseif ( ! empty($_COOKIE['langCode']))
        {
                $lang = strtolower($_COOKIE['langCode']);
 
                log_message('debug', 'Set language in Cookie: '.$lang);
        }
 
        // Still no Lang. Lets try some browser detection then
        elseif ( $config['checkHttpAcceptLanguage'] and ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
        {
                // explode languages into array
                $acceptLangs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
 
                $supportedLangs = array_keys($config['supportedLanguages']);
 
                log_message('debug', 'Checking browser languages: '.implode(', ', $acceptLangs));
 
                // Check them all, until we find a match
                foreach ($acceptLangs as $acceptLang)
                {
                        if (strpos($acceptLang, '-') === 2)
                        {
                                // Turn pt-br into br
                                $lang = strtolower(substr($acceptLang, 3, 2));
 
                                // Check its in the array. If so, break the loop, we have one!
                                if (in_array($lang, $supportedLangs))
                                {
                                        log_message('debug', 'Accept browser language: '.$acceptLang);
 
                                        break;
                                }
                        }
 
                        // Turn en-gb into en
                        $lang = strtolower(substr($acceptLang, 0, 2));
 
                        // Check its in the array. If so, break the loop, we have one!
                        if (in_array($lang, $supportedLangs))
                        {
                                log_message('debug', 'Accept browser language: ' . $acceptLang);
                                break;
                        }
                }
        }
 
        // If no language has been worked out - or it is not supported - use the default
        if (empty($lang) or ! array_key_exists($lang, $config['supportedLanguages']))
        {
                $lang = $config['supportedLanguages'];
 
                log_message('debug', 'Set language default: ' . $lang);
        }
 
        // Whatever we decided the lang was, save it for next time to avoid working it out again
        if (function_exists('get_instance') && !class_exists('session'))
        {
                $sessionLibrary = get_instance()->load->library('session');
                $sessionLibrary->session->set_userdata('langCode', $lang);
        }
 
        // Load CI config class
        $CIcConfig =& load_class('Config');
 
        // Set the language config. Selects the folder name from its key of 'en'
        $CIcConfig->set_item('language', $config['supportedLanguages'][$lang]['folder']);
 
        // Sets a constant to use throughout ALL of CI.
        define('AUTO_LANGUAGE', $lang);
 
        log_message('debug', 'Defined const AUTO_LANGUAGE: '. AUTO_LANGUAGE);
}
 
 
复制代码


Language.php
application/config/Language.php
PHP复制代码
 
$config['supportedLanguages'] = array(
        'en' => array(
                'name'                  => 'English',
                'folder'                => 'english',
                'direction'             => 'ltr',
                'codes'                 => array('en', 'english', 'en_US'),
        ),
        'ru' => array(
                'name'                  => 'Русский',
                'folder'                => 'russian',
                'direction'             => 'ltr',
                'codes'                 => array('rus', 'russian', 'ru_RU'),
        ),
        'cn' => array(
                'name'                  => '简体中文',
                'folder'                => 'chineseSimplified',
                'direction'             => 'ltr',
                'codes'                 => array('cn', 'chinese-simplified', 'zh_CN'),
        ),
        'tw' => array(
                'name'                  => '繁體中文',
                'folder'                => 'chinese_traditional',
                'direction'             => 'ltr',
                'codes'                 => array('tw', 'chinese-traditional', 'zh_TW'),
        ),
);
 
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| If no language is specified, which one to use? Must be in the array above
|
|    en
|
*/

$config['defaultLanguage'] = 'cn';
 
/*
|--------------------------------------------------------------------------
| Detect language using Accept-Language
|--------------------------------------------------------------------------
|
| Whether or not to take into account the Accept-Language client header
|
| Only turn it on for admin panel:
|       $config['checkHttpAcceptLanguage'] = (bool) preg_match('@\/admin(\/.+)?$@', $_SERVER['REQUEST_URI']);
|
*/

$config['checkHttpAcceptLanguage'] = TRUE;
 
 
 
复制代码


MYController.php
application/config/You controller.php
PHP复制代码
 
// Lock front-end language
//这里是检测在那里使用,我这里是在后台使用。
                if ( ! (is_a($this, 'AdminController') and ($siteLang = AUTO_LANGUAGE)))
                {
                        $siteLanguage = explode(',', Settings::get('sitePublicLang'));
 
                        if (in_array(AUTO_LANGUAGE, $siteLanguage))
                        {
                                $siteLang = AUTO_LANGUAGE;
                        }
                        else
                        {
                                $siteLang = Settings::get('siteLang');
                        }
                }
 
                echo Settings::get('siteLang');
 
                // We can't have a blank language. If there happens to be a blank language, let's default to English.
                if ( ! $siteLang )
                {
                        $siteLang = 'cn';
                }
 
                // What language us being used
                defined('CURRENT_LANGUAGE') or define('CURRENT_LANGUAGE', $siteLang);
 
                $langs = $this->config->item('supportedLanguages');
 
                $brocade['lang'] = $langs[CURRENT_LANGUAGE];
                $brocade['lang']['code'] = CURRENT_LANGUAGE;
                $this->load->vars($brocade);
 
 
复制代码



浏览器输入host.com/lang=cn试试吧。。。嘿嘿!确保语言包有当前的语言哦!
发表于 2016-5-8 11:29:59 | 显示全部楼层
我觉得该赞一下,大家之所以选择CI,就是想发挥一下自己的创造性,否则用其他的框架,什么都做好了,只要当搬运工即可。
 楼主| 发表于 2016-1-1 18:01:21 | 显示全部楼层
修复pickLanguage.php 正常使用
PHP复制代码
 
 
function pickLanguage()
{
        require APPPATH.'/config/language.php';
        $sessionLibrary = NULL;
 
        //      Load CI session class, if is class not exists.
        if (function_exists('get_instance') && ! class_exists('session'))
        {
                $sessionLibrary = get_instance()->load->library('session');
        }
 
        if ( ! is_object($sessionLibrary) )
        {
                show_error('Class Session not exists.', 500);
        }
 
        // Re-populate $_GET
        parse_str($_SERVER['QUERY_STRING'], $_GET);
 
        // If we've been redirected from HTTP to HTTPS on admin, ?session= will be set to maintain language
        if ($_SERVER['SERVER_PORT'] == 443 and ! empty($_GET['session']))
        {
                session_start($_GET['session']);
        }
 
        // Lang set in URL via ?lang=something
        if ( ! empty($_GET['lang']))
        {
                // Turn en-gb into en
                $lang = strtolower(substr($_GET['lang'], 0, 2));
 
                log_message('debug', 'Set language in URL via GET: '.$lang);
        }
 
        // Lang has already been set and is stored in a session
        elseif ( ! empty($sessionLibrary->session->userdata('langCode')))
        {
                $lang = $sessionLibrary->session->userdata('langCode');
 
                log_message('debug', 'Set language in Session: '.$lang);
        }
 
        // Lang has is picked by a user.
        elseif ( ! empty($_COOKIE['langCode']))
        {
                $lang = strtolower($_COOKIE['langCode']);
 
                log_message('debug', 'Set language in Cookie: '.$lang);
        }
 
        // Still no Lang. Lets try some browser detection then
        elseif ( $config['checkHttpAcceptLanguage'] and ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
        {
                // explode languages into array
                $acceptLangs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
 
                $supportedLangs = array_keys($config['supportedLanguages']);
 
                log_message('debug', 'Checking browser languages: '.implode(', ', $acceptLangs));
 
                // Check them all, until we find a match
                foreach ($acceptLangs as $acceptLang)
                {
                        if (strpos($acceptLang, '-') === 2)
                        {
                                // Turn pt-br into br
                                $lang = strtolower(substr($acceptLang, 3, 2));
 
                                // Check its in the array. If so, break the loop, we have one!
                                if (in_array($lang, $supportedLangs))
                                {
                                        log_message('debug', 'Accept browser language: '.$acceptLang);
 
                                        break;
                                }
                        }
 
                        // Turn en-gb into en
                        $lang = strtolower(substr($acceptLang, 0, 2));
 
                        // Check its in the array. If so, break the loop, we have one!
                        if (in_array($lang, $supportedLangs))
                        {
                                log_message('debug', 'Accept browser language: ' . $acceptLang);
                                break;
                        }
                }
        }
 
        // If no language has been worked out - or it is not supported - use the default
        if (empty($lang) or ! array_key_exists($lang, $config['supportedLanguages']))
        {
                $lang = $config['supportedLanguages'];
 
                log_message('debug', 'Set language default: ' . $lang);
        }
 
        // Whatever we decided the lang was, save it for next time to avoid working it out again
        $sessionLibrary->session->set_userdata('langCode', $lang);
 
        // Load CI config class
        $CIConfig =& load_class('Config');
 
        // Set the language config. Selects the folder name from its key of 'en'
        $CIConfig->set_item('language', $config['supportedLanguages'][$sessionLibrary->session->userdata('langCode')]['folder']);
 
        // Sets a constant to use throughout ALL of CI.
        define('AUTO_LANGUAGE', $sessionLibrary->session->userdata('langCode'));
 
        log_message('debug', 'Defined const AUTO_LANGUAGE: '. AUTO_LANGUAGE);
}
 
 
复制代码

发表于 2016-2-5 14:06:26 | 显示全部楼层
为什么不通过 CI自带的Lang函数呢
发表于 2017-5-20 22:39:53 | 显示全部楼层
ci的执行效率要高一些。

本版积分规则