|
| 1 | +# Localization |
| 2 | + |
| 3 | +json-api-server includes a basic localization system that allows you to |
| 4 | +customize error messages in your API responses. |
| 5 | + |
| 6 | +## Default Language |
| 7 | + |
| 8 | +By default, the server uses English for all error messages. These are defined in |
| 9 | +the `Tobyz\JsonApi\Translation\EnglishCatalogue` class. |
| 10 | + |
| 11 | +## Customizing Messages |
| 12 | + |
| 13 | +You can customize messages in two ways: |
| 14 | + |
| 15 | +### Merging Custom Messages |
| 16 | + |
| 17 | +To override specific messages while keeping the defaults: |
| 18 | + |
| 19 | +```php |
| 20 | +$api = new JsonApi(); |
| 21 | + |
| 22 | +$api->messages([ |
| 23 | + 'resource.not_found' => 'The requested resource could not be found', |
| 24 | + 'pagination.size_exceeded' => 'The requested page size is too large', |
| 25 | +]); |
| 26 | +``` |
| 27 | + |
| 28 | +This will merge your custom messages with the default English messages. |
| 29 | + |
| 30 | +### Using a Custom Translator |
| 31 | + |
| 32 | +For complete control over localization, you can provide your own translator |
| 33 | +implementation: |
| 34 | + |
| 35 | +```php |
| 36 | +use Tobyz\JsonApiServer\Translation\TranslatorInterface; |
| 37 | + |
| 38 | +class CustomTranslator implements TranslatorInterface |
| 39 | +{ |
| 40 | + public function translate(string $key, array $replacements = []): string |
| 41 | + { |
| 42 | + // Your custom translation logic here |
| 43 | + return $translation; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +$api = new JsonApi(); |
| 48 | +$api->setTranslator(new CustomTranslator()); |
| 49 | +``` |
| 50 | + |
| 51 | +## Message Keys |
| 52 | + |
| 53 | +Messages support placeholder replacements using the `:placeholder` syntax. The |
| 54 | +replacement values are passed as an array: |
| 55 | + |
| 56 | +```php |
| 57 | +$context->translate('resource.not_found', ['identifier' => 'users']); |
| 58 | +// Results in: "Resource not found: users" |
| 59 | +``` |
| 60 | + |
| 61 | +## Using Localization in Custom Code |
| 62 | + |
| 63 | +You can access the localization system in your custom code through the Context |
| 64 | +object: |
| 65 | + |
| 66 | +```php |
| 67 | +use Tobyz\JsonApiServer\Context; |
| 68 | + |
| 69 | +$message = $context->translate('custom.key', ['name' => 'value']); |
| 70 | +``` |
0 commit comments