DEV Community

Hadi Akbarzadeh
Hadi Akbarzadeh

Posted on

Light Localization for PHP - Translations

My simple #PHP #library for localization

Github

A light weight and path-based PHP localization library that translations are loaded up when needed.

Top comments (1)

Collapse
 
xwero profile image
Info Comment hidden by post author - thread only accessible via permalink
david duymelinck • Edited

I am not a big fan of using arrays as config if it only has one level. So as an exercise I thought about the most light weight way to have translations.

I came up with enums.

// Translations/En/Main.php
enum Main: string {
    use Translation;

    case Hello = 'Hello you';
    case HelloName = 'Hello {{name}}';
}
Enter fullscreen mode Exit fullscreen mode
// Translations/Nl/Main.php
enum Main: string {
    use Translation;

    case Hello = 'Hallo';
}
Enter fullscreen mode Exit fullscreen mode
// Translations/Translation.php

trait Translation {
    public static function get(string $case, array $replacements = [], $fallback = null): string {
        try {
            $output = self::{$case}->value;

            if(empty($replacements)) {
                return $output;
            }

            $search = array_map(fn($search) => '{{'.$search.'}}', array_keys($replacements));

            return str_replace($search, array_values($replacements), $output);
        } catch(\Error $e) {
            if($fallback) {
                return $fallback::get($case, $replacements);
            }

            return "!$case!";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This setup allows you to use it as in following examples;

Translations\En\Main::Hello->value;
// or
Translations\En\Main::get('Hello');
Enter fullscreen mode Exit fullscreen mode
Translations\En\Main::get('HelloName', ['name' => 'Hadi']);
Enter fullscreen mode Exit fullscreen mode
Translations\Nl\Main::get('HelloName', ['name' => 'Hadi'], 'Translations\En\Main');
Enter fullscreen mode Exit fullscreen mode

When the output requires multiple scopes, just create an array and get the string from the scope you want.

PS: this only works in PHP 8.3 because the trait uses dynamic class constant fetch.

Some comments have been hidden by the post's author - find out more