基于Lumen-i18n

i18n(其来源是英文单词 internationalization的首末字符in18为中间的字符数)是 “国际化” 的简称

通常与i18n相关的还有L10n“本地化” 的简称)

核心代码

  • app/Traits/Tool.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php

namespace App\Traits;

class Tool
{
public static function sysMsg($key, $lang = 'zh')
{
$lang = $_REQUEST['lang'] ?? 'zh';

if (isset($GLOBALS['__sys_msg'])
&& is_array($GLOBALS['__sys_msg'])
&& $GLOBALS['__sys_msg']
) {
$msg = $GLOBALS['__sys_msg'];
} else {
$msg = [];
$langPath = resource_path().'/sys_msg/';
$path = $langPath.$lang;
if (! file_exists($path)) {
$path = $langPath.'zh';
}

if (file_exists($path)) {
$fsi = new \FilesystemIterator($path);
foreach ($fsi as $file) {
if ($file->isFile() && 'php' == $file->getExtension()) {
$_msg = include $file->getPathname();
if($_msg && is_array($_msg)) {
$msg = array_merge($_msg, $msg);
}
}
}

$GLOBALS['__sys_msg'] = $msg;
}
}

return $msg[$key]
?? (
('zh' == $lang)
? '服务器繁忙, 请稍后再试'
: 'Service is busy or temporarily unavailable.'
);
}
}
  • 新建: resources/sys_msg/en/Main.php
1
2
3
4
5
<?php

return [
'SYS_MSG_TEST' => 'Test the system message i18n',
];
  • 新建: resources/sys_msg/zh/Main.php
1
2
3
4
5
<?php

return [
'SYS_MSG_TEST' => '测试一下系统消息i18n',
];

测试

  • app/Http/Controllers/TestController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php

namespace App\Http\Controllers;

use App\Traits\Tool;

class TestController extends Controller
{
public function test_i18n()
{
return Tool::sysMsg('SYS_MSG_TEST');
// 测试一下系统消息i18n

return Tool::sysMsg('SYS_MSG_TEST', 'en');
// Test the system message i18n
}
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :