Skip to content

Commit 554326d

Browse files
tboronczykTimothy Boronczyk
authored and
Timothy Boronczyk
committed
update README.md
1 parent eeb5940 commit 554326d

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

README.md

+41-3
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
[![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)
44

55
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.
711

8-
## Usage
12+
## Basic Example
913

1014
use Boronczyk\LocalizationMiddleware;
1115

@@ -16,8 +20,42 @@ and various other localization tasks.
1620
$app->get('/', function ($req, $resp, $args) {
1721
$attrs = $req->getAttributes();
1822
$locale = $attrs['locale'];
23+
return $resp->write("The locale is $locale.");
1924
});
2025

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+
2159
## Configurable Behavior
2260

2361
The middleware component’s behavior is configurable though the following
@@ -91,7 +129,7 @@ methods:
91129
Sets the name for a URI parameter to specify the locale. The default name
92130
is `locale`.
93131

94-
$middleware->setReqAttrName('lang');
132+
$middleware->setUriParamName('lang');
95133

96134
https://example.com/mypage?lang=es_MX
97135

0 commit comments

Comments
 (0)