3
3
[ ![ Build Status] ( https://travis-ci.org/tboronczyk/localization-middleware.svg?branch=master )] ( https://travis-ci.org/tboronczyk/localization-middleware ) [ ![ codecov] ( https://codecov.io/gh/tboronczyk/localization-middleware/branch/master/graph/badge.svg )] ( https://codecov.io/gh/tboronczyk/localization-middleware )
4
4
5
5
PSR-7 middleware to assist primarily with language-based content negotiation
6
- and various other localization tasks.
6
+ and various other localization tasks. It determines the appropriate locale
7
+ based on the client’s request and sets an attribute on the request object to
8
+ make the value available to the rest of your application. It’s callback hook
9
+ offers a convenient way to initialize other libraries or execute code based on
10
+ the locale value.
7
11
8
- ## Usage
12
+ ## Basic Example
9
13
10
14
use Boronczyk\LocalizationMiddleware;
11
15
@@ -16,8 +20,42 @@ and various other localization tasks.
16
20
$app->get('/', function ($req, $resp, $args) {
17
21
$attrs = $req->getAttributes();
18
22
$locale = $attrs['locale'];
23
+ return $resp->write("The locale is $locale.");
19
24
});
20
25
26
+ ## More Advanced Example
27
+
28
+ use Boronczyk\LocalizationMiddleware;
29
+
30
+ $availableLocales = ['en_US', 'fr_CA', 'es_MX', 'eo'];
31
+ $defaultLocale = 'en_US';
32
+ $middleware = new LocalizationMiddleware($availableLocales, $defaultLocale);
33
+
34
+ $middleware->setSearchOrder([
35
+ LocationMiddleware::FROM_URI_PATH,
36
+ LocationMiddleware::FROM_URI_PARAM,
37
+ LocationMiddleware::FROM_COOKIE,
38
+ LocationMiddleware::FROM_HEADER
39
+ ]);
40
+ $middleware->setCallback(function (string $locale) {
41
+ putenv("LANG=$locale");
42
+ setlocale(LC_ALL, $locale);
43
+ bindtextdomain('messages', 'Locale');
44
+ bind_textdomain_codeset('messages', 'UTF-8');
45
+ textdomain('messages');
46
+ });
47
+ $middleware->setUriParamName('hl');
48
+
49
+ $app->add($middleware);
50
+
51
+ $app->get('/', function ($req, $resp, $args) {
52
+ $attrs = $req->getAttributes();
53
+ $locale = $attrs['locale'];
54
+ $text = sprintf(_('The locale is %s.'), $locale);
55
+ return $resp->write($text);
56
+ });
57
+
58
+
21
59
## Configurable Behavior
22
60
23
61
The middleware component’s behavior is configurable though the following
@@ -91,7 +129,7 @@ methods:
91
129
Sets the name for a URI parameter to specify the locale. The default name
92
130
is ` locale ` .
93
131
94
- $middleware->setReqAttrName ('lang');
132
+ $middleware->setUriParamName ('lang');
95
133
96
134
https://example.com/mypage?lang=es_MX
97
135
0 commit comments