codeigniter_CodeIgniter中的多语言支持

codeigniter

Multi-language support, also known as internationalization, is a key feature of modern web applications. Most of the full-stack PHP frameworks come with multi-language support which enables us to dynamically present our application’s interface in different languages without duplicating the existing source code for each language. Today we’re going to discuss how we can enable multiple languages using CodeIgniter as well as a few tricks to customize the core functionality.

多语言支持(也称为国际化)是现代Web应用程序的关键功能。 大多数全栈PHP框架都提供了多语言支持,这使我们能够以不同语言动态显示应用程序的界面,而无需为每种语言复制现有的源代码。 今天,我们将讨论如何使用CodeIgniter启用多种语言,以及一些自定义核心功能的技巧。

配置多语言支持 (Configuring Multi-Language Support)

First we need to configure the necessary files before we can start using language support. The CodeIgniter config file, located in the application/config directory, contains an option called language which defines the default language of the application.

首先,我们需要配置必要的文件,然后才能开始使用语言支持。 位于application/config目录中的CodeIgniter配置文件包含一个名为language的选项,该选项定义了应用程序的默认语言。

<?php
$config['language'] = 'english';

We also need to create the actual files which contain our messages in different languages. These files need to be placed inside the application/language directory with a separate directory for each language. For example, English language files should reside in the application/language/english directory, and French language files should be located in application/language/french.

我们还需要创建包含不同语言消息的实际文件。 这些文件需要放置在application/language目录中,每种语言都有一个单独的目录。 例如,英语文件应位于application/language/english目录中,而法语文件应位于application/language/french

Let’s create some language files that contain error messages for a sample application. Create the file english/message_lang.php (it’s important that all of the language files have the suffix _lang.php). The following code contains some sample entries for the content of our language file:

让我们创建一些语言文件,其中包含示例应用程序的错误消息。 创建文件english/message_lang.php (重要的是所有语言文件都带有后缀_lang.php )。 以下代码包含一些有关我们语言文件内容的示例条目:

<?php
$lang["msg_first_name"] = "First Name";
$lang["msg_last_name"] = "Last Name";
$lang["msg_dob"] = "Date of Birth";
$lang["msg_address"] = "Address";

Of course, you can have multiple language files inside a single language directory. It’s recommended to group your messages into different files based on their context and purpose, and prefix your message keys with a file-specific keyword for consistency.

当然,您可以在一个语言目录中包含多个语言文件。 建议根据消息的上下文和用途将消息分组到不同的文件中,并为消息密钥添加特定于文件的关键字,以确保一致性。

Another way is to create separate message files for each controller. The advantage of this technique is that only the required messages are loaded instead of an entire language file which can create a certain level of performance overhead.

另一种方法是为每个控制器创建单独的消息文件。 此技术的优点是仅加载所需的消息,而不是整个语言文件,这会造成一定程度的性能开销。

加载语言文件 (Loading the Language Files)

Even though we create language files, they are not effective until we load them inside controllers. The following code shows how we can load the files inside a controller:

即使我们创建语言文件,它们也只有在将它们加载到控制器中后才有效。 以下代码显示了如何在控制器内部加载文件:

<?php
class TestLanguage extends CI_Controller
{
    public function __construct() {
        parent::__construct();   	 
        $this->lang->load("message","english");
    }

    function index() {
        $data["language_msg"] = $this->lang->line("msg_hello_english");
        $this->load->view('language_view', $data);
    }
}

We usually work with the language files within the controllers and views (using language files inside models is not such a good thing). Here we’ve used a controller’s constructor to load the language file so it can be used throughout the whole class, then we reference it in the class’ index() method.

我们通常在控制器和视图中使用语言文件(在模型内部使用语言文件不是一件好事)。 在这里,我们使用了控制器的构造函数来加载语言文件,以便可以在整个类中使用它,然后在类的index()方法中对其进行引用。

The first parameter to the lang->load() method will be the language’s filename without the _lang suffix. The second paramter, which is optional, is the language directory. It will point to default language in your config if it’s not provided here.

lang-> load()方法的第一个参数将是不带_lang后缀的语言文件名。 第二个参数(可选)是语言目录。 如果此处未提供,它将指向配置中的默认语言。

We can directly reference the entries of a language file using the lang->line() method and assign it’s return to the data passed into the view templates. Inside the view, we can then use the above language message as $language_msg.

我们可以使用lang->line()方法直接引用语言文件的条目,并将其返回值分配给传递到视图模板的数据。 在视图内部,我们可以将以上语言消息用作$language_msg

There may be an occasion when we need to load language files directly from the views as well. For example, using language items for form labels might be considered a good reason for directly loading and accessing messages inside views. It’s possible to use the same access method for these files inside views as inside controllers.

有时候,我们也需要直接从视图中加载语言文件。 例如,将语言项用于表单标签可能被认为是直接在视图内直接加载和访问消息的良好原因。 可以在视图内部对这些文件使用与控制器内部相同的访问方法。

<?php
$this->lang->line("msg_hello_english");

Though it works perfectly, it could be confusing to have $this when our view template code isn’t an actual class. We can also use the following code with the support of the language helper to load language entries inside views, which gives us cleaner code.

尽管它可以完美工作,但是当我们的视图模板代码不是实际的类时,使用$this可能会造成混淆。 我们还可以在语言帮助器的支持下使用以下代码在视图内加载语言条目,这使我们的代码更简洁。

<?php
lang("msg_view_english");

That’s basically all you need to know to get started working with CodeIgniter language files. But even though this is simple enough, it’s unnecessary and duplicated effort to load the necessary language files in each of the controllers, especially if your project contains hundreds of classes. Luckily, we can use CodeIgniter hooks to build a quick and effective solution for loading language files automatically for each controller.

基本上这就是您开始使用CodeIgniter语言文件所需要知道的全部内容。 但是,即使这很简单,也不必在每个控制器中加载必要的语言文件,也无需进行重复的工作,尤其是在您的项目包含数百个类的情况下。 幸运的是,我们可以使用CodeIgniter挂钩构建快速有效的解决方案,以自动为每个控制器加载语言文件。

向挂钩分配语言加载职责 (Assigning Language Loading Responsibilities to Hooks)

CodeIgniter calls a few built-in hooks as part of its execution process. You can find a complete list of hooks in the user guide. We’ll use the post_controller_constructor hook which is called immediately after our controller is instantiated and prior to any other method calls.

CodeIgniter在执行过程中会调用一些内置的挂钩。 您可以在用户指南中找到钩子的完整列表。 我们将使用post_controller_constructor钩子,该钩子在实例化控制器之后且在任何其他方法调用之前立即被调用。

We enable hooks in our application by setting the enable_hooks parameter in the main config file.

通过在主配置文件中设置enable_hooks参数,可以在应用程序中启用挂钩。

<?php
$config['enable_hooks'] = TRUE;

Then we can open the hooks.php file inside the config directory and create a custom hook as shown in the following code:

然后,我们可以打开config目录中的hooks.php文件,并创建一个自定义钩子,如以下代码所示:

<?php
$hook['post_controller_constructor'] = array(
    'class' => 'LanguageLoader',
    'function' => 'initialize',
    'filename' => 'LanguageLoader.php',
    'filepath' => 'hooks'
);

This defines the hook and provides the necessary information to execute it. The actual implementation will be created in a custom class inside the application/hooks directory.

这定义了钩子,并提供了执行钩子所需的信息。 实际的实现将在application/hooks目录内的自定义类中创建。

<?php
class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
        $ci->lang->load('message','english');
    }
}

In here we don’t have the access to the language library using $this->lang, so we need to get the CI object instance using the get_instance() function, and then we load the language as we did earlier. Now the language file will be available for every controller of our application without the need to manually load it inside the controllers.

在这里,我们无法使用$this->lang来访问语言库,因此我们需要使用get_instance()函数获取CI对象实例,然后像之前一样加载语言。 现在,该语言文件可用于我们应用程序的每个控制器,而无需在控制器内部手动加载它。

在不同语言之间切换 (Switching Between Different Languages)

Once we have established support for multiple languages, a link for each language can be provided to the user, generally in one of our application’s menus, which the users can click and switch the language. A session or cookie value can be used to keep track of the active language.

一旦我们建立了对多种语言的支持,通常可以在我们应用程序的菜单之一中向用户提供每种语言的链接,用户可以单击并切换语言。 会话或cookie值可用于跟踪活动语言。

Let’s see how we can manage language switching using the hooks class we generated earlier. First we need to create a class to switch the language; we’ll be using a separate controller for this as shown below:

让我们看看如何使用我们之前生成的钩子类来管理语言切换。 首先,我们需要创建一个类来切换语言。 我们将为此使用单独的控制器,如下所示:

<?php
class LangSwitch extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    function switchLanguage($language = "") {
        $language = ($language != "") ? $language : "english";
        $this->session->set_userdata('site_lang', $language);
        redirect(base_url());
    }
}

Then we need to define links to switch each of the available languages.

然后,我们需要定义链接以切换每种可用语言。

<a href='<?php echo $base_url; ?>langswitch/switchLanguage/english'>English</a>
<a href='<?php echo $base_url; ?>langswitch/switchLanguage/french'>French</a>

Whenever the user chooses a specific language, the switchLanguage() method of the LangSwitch class will assign the selected languages to the session and redirect the user to the home page.

每当用户选择特定语言时, LangSwitch类的switchLanguage()方法都会将所选语言分配给会话,并将用户重定向到主页。

Now the active language will be changed in the session, but still it won’t get affected until we load the specific language file for the active language. We also need to modify our hooks class to load the language dynamically from the session.

现在,活动语言将在会话中更改,但是在我们为活动语言加载特定语言文件之前,它不会受到影响。 我们还需要修改钩子类以从会话中动态加载语言。

<?php
class LanguageLoader
{
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');

        $site_lang = $ci->session->userdata('site_lang');
        if ($site_lang) {
            $ci->lang->load('message',$ci->session->userdata('site_lang'));
        } else {
            $ci->lang->load('message','english');
        }
    }
}

Inside the LanguageLoader class we get the active language and load the necessary language files, or we load the default language if the session key is absent. We can load multiple language files of a single language inside this class.

LanguageLoader类中,我们获取活动语言并加载必要的语言文件,或者如果缺少会话密钥,则加载默认语言。 我们可以在此类中加载单一语言的多个语言文件。

结论 (Conclusion)

Most of the full-stack PHP frameworks come with multi-language support which enables us to easily present our application’s interface in different languages. In this article we saw how to provide multiple languages using CodeIgniter. Of course, there are other ways of building up multi-language solutions, so feel free to discuss the best practices and experiences you had in implementing multi-language support in CodeIgniter and even in other frameworks. I’m looking forward to hearing from you!

大多数全栈PHP框架都带有多语言支持,这使我们能够轻松地以不同语言呈现应用程序的界面。 在本文中,我们看到了如何使用CodeIgniter提供多种语言。 当然,还有其他构建多语言解决方案的方法,因此可以随意讨论您在CodeIgniter甚至其他框架中实现多语言支持所拥有的最佳实践和经验。 期待收到你的消息!

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/multi-language-support-in-codeigniter/

codeigniter

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值