search
HomeBackend DevelopmentPHP TutorialDetailed explanation of Laravel's localization module

Detailed explanation of Laravel's localization module

Jan 03, 2018 pm 03:50 PM
laravelphpStudy tutorial

This article mainly introduces you to the relevant information about the localization module of the Laravel learning tutorial. The article introduces it to you in great detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it can follow Come and learn with me. I hope to be helpful.

Preface

This article mainly introduces to you the relevant content about Laravel localization module, and shares it for your reference and study. There is not much to say. Having said that, let’s take a look at the detailed introduction.

This article is based on the analysis and writing of the localized module code of Laravel 5.4 version;

Module composition

The following figure shows the relationship between the various files of the localization module and gives a brief description;


  • TranslationServiceProvider
    The service provider of the localization module is not only the entrance to a module, but also the center of interaction with the IOC container; register the translator instance translation.loader, register the translation management instance translator, and declare the delayed loading service;

  • Translator
    Translation management class;

  • MessageSelector
    The message filter selects the appropriate message by judging the complex value; for example, the message content is like this: {0} no | [1,19] some | [20,*] a lot, the number we pass is 18, then the last one selected The message is "some";

  • LoaderInterface
    Translator interface; declares three methods load, addNamespace, namespaces;

  • FileLoader
    Inherits LoaderInterface and obtains localized resource data from files;

  • ArrayLoader
    Inherits LoaderInterface and uses arrays to maintain localized resource data in memory;

Configuration instructions

The parameters related to this module in the config configuration directory are only locale and fallback_locale in the app.php file;

locale indicates what the default localization language is, so that translations will be obtained first from the language resource directory (Conversion) content;
If the language represented by the locale does not exist, the fallback_locale alternative language is used;

The author's locale is zh_CN, and the fallback_locale is en;

Function introduction

The global language resource directory is under the resources/lang of the project. Each subdirectory is named after the language, such as en, zh_CN, etc.;

Other subdirectories are named after namespaces, which are supplementary replacements for third-party loading library resource files;

There may also be Json files such as en.json and zh_CN, and projects sometimes import them from Json File reading data, these data come from this existing Json file;

Translate global language resources

The author's language resource root directory resources/ There is zh_CN/validation.php under lang, the content is as follows

<?php
return [
 &#39;accepted&#39;  => &#39;:attribute 必须接受。&#39;,
 &#39;active_url&#39;  => &#39;:attribute 不是一个有效的网址。&#39;,
 &#39;after&#39;  => &#39;:attribute 必须是一个在 :date 之后的日期。&#39;,
 ......
];

By calling the code

app(&#39;translator&#39;)->trans(&#39;validation.accepted&#39;, [&#39;attribute&#39; => &#39;用户名&#39;])

or the global help function trans

trans(&#39;validation.accepted&#39;, [&#39;attribute&#39; => &#39;用户名&#39;])

output "The user name must be accepted.";

The calling process is as follows:

  • Parse the key name: parse the key name into an array ($namespace = '*', $ group = 'validation', $item = 'accepted'); namespace is *, which means it is under the global namespace; group, group, is actually the file name, and one file is a group; item means element;

  • Get the language array: $locale here is null, so what is returned is an array of default and backup languages, that is, ['zh_CN', 'en']; and perform a for loop , enter the language resource directory to search for the required element value. If found, break;

  • Load resources: Because the namespace is *, the root directory of the located resource is resources/lang; language is zh_CN, so the subdirectory is zh_CN; the group name is validation. At this time, all the contents in the resources/lang/zh_CN/validation.php file are loaded into the memory and saved.$this->loaded [$namespace][$group][$locale] = $lines;

  • Get resources and replace parameters: through the Arr::get method Get element value from $this->loaded[$namespace][$group][$locale]: attribute must be accepted. ;At this time, the parameter array is not empty, loop replacement, and get the result "The user name must be accepted.";

Translate languages ​​with namespaces Resources

The author created the vendor/Faker/Provider/zh_CN/Internet.php file under the language resource root directory resource/lang, with the following content:

<?php
return [
 &#39;message&#39; => &#39;hello, Faker/Provider&#39;,
 ......
];

At the same time, manually register the resource root directory location of the third-party plug-in (that is, with namespace) in Translator;

app(&#39;translator&#39;)->addNamespace(&#39;Faker/Provider&#39;, base_path(&#39;vendor/xx/resource/lang&#39;))

Now, obtain the resource with namespace;

trans(&#39;Faker/Provider::Internet.message&#39;);

Output 'hello , Faker/Provider';

The calling process is as follows:

  • 解析键名:将键名进行解析成数组 ($namespace = 'Faker/Provider', $group = 'Internet', $item = 'message');

  • 获取语言数组: 这里的$locale为null,所以返回的是默认与备用语言组成的数组,也就是['zh_CN', 'en'];并进行for循环,进入语言资源目录中寻找需要的元素值,如果找到,即 break;

  • 加载资源:因为命名空间为Faker/Provider,此时会分两步;第一步读取第三方插件资源库下的信息,这时读取命名空间注册的根目录为base_path('vendor/xx/resource/lang'),就读取base_path('vendor/xx/resource/lang')/zh_CN/Internet.php内容,文件不存在,返回空数组;第二步读取全局语言资源,进行补充,也就是读取base_path('resource/lang/vendor/Faker/Provider')/zh_CN/Internet.php; 最后进行保存 $this->loaded[$namespace][$group][$locale] = $lines;

  • 获取资源,并替换参数:通过Arr::get方法从$this->loaded[$namespace][$group][$locale]中获取元素值" hello, Faker/Provider";此时,参数数组为空,直接返回结果 "hello, Faker/Provider";

翻译Json文件中的资源

笔者在语言资源根目录resource/lang下,创建zh_CN.json文件,内容如下:

{
 "name": "zh_CN.json",
 "place": "../resources/lang/zh_CN.json"
}

现在,获取Json文件中的name值;

trans(&#39;*.name&#39;)

输出 "zh_CN.json";

调用过程如下:

  • 解析键名:将键名进行解析成数组 ($namespace = '*', $group = '*', $item = 'name');

  • 获取语言数组: 这里的$locale为null,所以返回的是默认与备用语言组成的数组,也就是['zh_CN', 'en'];并进行for循环,进入语言资源目录中寻找需要的元素值,如果找到,即 break;

  • 加载资源:因为命名空间为*,且组也为*,这时会读取语言根目录下,名字为语言值的Json文件;此时会读取resource/lang/zh_CN.json,将读取的内容,进行保存 $this->loaded[$namespace][$group][$locale] = $lines;

  • 获取资源,并替换参数:通过Arr::get方法从$this->loaded[$namespace][$group][$locale]中获取元素值"zh_CN.json";此时,参数数组为空,直接返回结果 "zh_CN.json";

运行时绑定资源

资源的内容除了放在文件中,用到的时候在读取,也可以在项目运行时,存放;

以resources/lang/zh_CN/validation.php为例,现在想要在运行时,给这个组添加一个新的元素叫 extra,需要指定放在哪个语言下,可以这样写

app(&#39;translator&#39;)->addLines(array(&#39;validation.extra&#39; => &#39;测试添加额外数据&#39;), &#39;zh_CN&#39;);

现在可以获取这个新添加的元素值

trans(&#39;validation.extra&#39;)

复数资源过滤

笔者通过 运行时绑定资源 添加一条翻译内容:

app(&#39;translator&#39;)->addLines(array(&#39;validation.extra&#39; => &#39;{0}没有|[1,19]一些|[20,*]很多&#39;), &#39;zh_CN&#39;);

如果通过trans('validation.extra') ,获取的就是整条翻译内容,不是我们所期望的;用choice方法:

app('translator')->choice('validation.extra', 0) 得到 没有;

app('translator')->choice('validation.extra', 18) 得到 一些;

app('translator')->choice('validation.extra', 20) 得到 很多;

可以将app('translator')->choice(...)简写成全局帮助函数trans_choice(...);

相关推荐:

laravel编写APP接口(API)

在laravel5里如何使用try catch?

Laravel 5.5的可相应接口如何使用?

The above is the detailed content of Detailed explanation of Laravel's localization module. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment