Laravel localization module
Preface
This article mainly introduces the Laravel localization module for your reference and learning. Let's take a look at the detailed introduction.
This article analyzes and writes the code of the localization module based on Laravel 5.4;
Module composition
The relationship between each file in the localization module is displayed and briefly described;
- TranslationServiceProvider
The service provider of the localization module is both a module entry and a center for interaction with IOC containers. 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 determining the number of duplicates. For example, the message content is {0} Not | [1, 19] | [20, *] many, the number we pass is 18, so the last message selected is "some ";
- LoaderInterface
The translator interface declares three methods: load, addNamespace, and namespaces;
- FileLoader
Inherits LoaderInterface and obtains localized resource data from files;
- ArrayLoader
Inherits LoaderInterface and maintains local resource data with arrays in the memory;
Configuration instructions
In the config configuration directory, only locale and fallback_locale in the app. php file are related to the parameters of this module;
Locale indicates what the default localization language is, which gives priority to obtaining translation (conversion) content from the Language Resource Directory;
If locale indicates that the language does not exist, use fallback_locale;
The author's locale is zh_CN, and fallback_locale is en;
Features
The Global Language Resource Directory is under resources/lang of the project. Each subdirectory is named in the language, such as en and zh_CN;
In addition, some sub-directories are named in the namespace and supplement and replace the source file for third-party library loading;
Json files such as en. Json and zh_CN may also exist. Projects sometimes read data from Json files, all of which come from this existing Json file;
Translation of Global Language Resources
The root directory of the author's language resources is zh_CN/validation. php under resources/lang. The content is as follows:
<? Phpreturn ['accessted' => ': attribute must be accepted. ', 'Active _ url' =>': attribute is not a valid url. ', 'After' =>': attribute must be a date after: date. ',...];
Call the code
App ('translator')-> trans ('validation. accepted', ['attribute' => 'username'])
Or the Global Help function trans
Trans ('validation. accessted', ['attribute' => 'username'])
Output "the user name must be accepted. ";
The call process is as follows:
- Resolution key name: parses the key name into an array (
$namespace = '*', $group = 'validation', $item = 'accepted'); Namespace is *, which indicates that it is under the global namespace; group, group, is actually the file name, a file is a group; item is the meaning of the element;
- Obtain the language array: $ locale is null, so the returned result is an array consisting of the default and standby languages, that is, ['zh _ cn', 'en']; and perform a for loop to enter the Language Resource Directory to find the required element value. If it is found, it is break;
- Load resources: Because the namespace is *, locate the resource root directory as resources/lang; the language is zh_CN, so the subdirectory is zh_CN; the group name is validation, resources/lang/zh_CN/validation. all content in the PHP file is loaded into the memory and saved.
$this->loaded[$namespace][$group][$locale] = $lines;
- Obtain the resource and replace the parameter
Arr::getMethod slave$this->loaded[$namespace][$group][$locale]Element value: attribute must be accepted .; In this case, the parameter array is not empty and is replaced cyclically. The result is as follows: "The user name must be accepted. ";
Translate language resources with namespaces
In resource/lang, the root directory of the language resource is used to create the file vendor/Faker/Provider/zh_CN/Internet. php. The content is as follows:
<?phpreturn [ 'message' => 'hello, Faker/Provider', ......];
At the same time, manually register the third-party plug-in (that is, the resource root directory location with namespace) in the Translator;
app('translator')->addNamespace('Faker/Provider', base_path('vendor/xx/resource/lang'))
Now, retrieve resources with namespaces;
trans('Faker/Provider::Internet.message');
Output 'hello, Faker/provider ';
The call process is as follows:
- Resolution key name: parses the key name into an array.
($namespace = 'Faker/Provider', $group = 'Internet', $item = 'message');
- Obtain the language array: $ locale is null, so the returned result is an array consisting of the default and standby languages, that is, ['zh _ cn', 'en']; and perform a for loop to enter the Language Resource Directory to find the required element value. If it is found, it is break;
- Load resources: Because the namespace is Faker/Provider, two steps are taken. The first step is to read the information under the third-party plug-in resource library, at this time, read the root directory registered in the namespace as base_path ('vendor/xx/resource/lang '), and then read base_path ('vendor/xx/resource/lang ') /zh_CN/Internet. php content. If the file does not exist, an empty array is returned. The second step reads the Global Language Resource and supplements it, that is, reads it.
base_path('resource/lang/vendor/Faker/Provider')/zh_CN/Internet.php; Save$this->loaded[$namespace][$group][$locale] = $lines;
- Obtain the resource and replace the parameter
Arr::getMethod slave$ This-> loaded [$ namespace] [$ group] [$ locale]Obtain the element value "hello, Faker/Provider". If the parameter array is empty, the system returns the result "hello, Faker/Provider ";
Translate resources in a Json File
The author creates the zh_CN.json file under the language resource root directory resource/lang. The content is as follows:
{ "name": "zh_CN.json", "place": "../resources/lang/zh_CN.json"}
Now, get the name value in the Json file;
trans('*.name')
Output "zh_CN.json ";
The call process is as follows:
- Resolution key name: parses the key name into an array.
($namespace = '*', $group = '*', $item = 'name');
- Obtain the language array: $ locale is null, so the returned result is an array consisting of the default and standby languages, that is, ['zh _ cn', 'en']; and perform a for loop to enter the Language Resource Directory to find the required element value. If it is found, it is break;
- Load resources: Because the namespace is * and the group is *, the system reads the Json file named language value under the root directory of the language. At this time, the system reads resource/lang/zh_CN.json, save the read content
$this->loaded[$namespace][$group][$locale] = $lines;
- Obtain the resource and replace the parameter: Use the Arr: get method
$this->loaded[$namespace][$group][$locale]Obtain the element value "zh_CN.json"; in this case, the parameter array is empty and the result "zh_CN.json" is directly returned ";
Bind resources at runtime
In addition to files, resources can be read or stored during project running;
Taking resources/lang/zh_CN/validation. php as an example, if you want to add a new element called extra to this group at runtime, You need to specify the language in which you want to write
App ('translator')-> addLines (array ('validation. extra '=> 'test adding additional data'), 'zh _ cn ');
Now you can get the new element value.
trans('validation.extra')
Filter plural Resources
The author adds a translation entry by binding resources during the runtime:
App ('translator')-> addLines (array ('validation. extra '=>' {0} None | [] Some | [20, *] Many '), 'zh _ cn ');
Iftrans('validation.extra')The entire translation content is obtained, which is not what we expect. The choice method is used:
app('translator')->choice('validation.extra', 0) No;
app('translator')->choice('validation.extra', 18) Get some;
app('translator')->choice('validation.extra', 20) Get a lot;
You can setapp('translator')->choice(...)The Global Help function trans_choice (...);
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.