Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

I18N Laravel Package

yiisoft/i18n

Yii i18n provides lightweight internationalization utilities for PHP: a BCP 47 Locale value object to parse and modify locale parts, build locale strings, and derive fallbacks, plus a stateful LocaleProvider service for managing the current and default locale.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yiisoft/i18n
    

    Add to composer.json under require-dev if only for testing:

    "yiisoft/i18n": "^2.0"
    
  2. First Use Case: Locale Creation

    use Yiisoft\I18n\Locale;
    
    $locale = Locale::create('en-US'); // BCP 47 format
    echo $locale->getLanguage(); // "en"
    echo $locale->getRegion();   // "US"
    
  3. Where to Look First

    • Documentation (if available)
    • src/Locale.php (core class)
    • tests/ for usage examples

Implementation Patterns

Core Workflows

  1. Locale Parsing & Validation

    $locale = Locale::create('fr-CA-u-co-phonetic');
    if ($locale->isValid()) {
        // Use locale
    }
    
  2. Locale Comparison

    $locale1 = Locale::create('en-GB');
    $locale2 = Locale::create('en-US');
    
    if ($locale1->equals($locale2, Locale::COMPARE_LANGUAGE)) {
        // Same language, different regions
    }
    
  3. Locale Normalization

    $normalized = Locale::create('en-us')->normalize(); // "en-US"
    
  4. Integration with Laravel

    • Store user locale in session():
      session(['locale' => $request->get('locale', 'en-US')]);
      
    • Create a helper:
      function getLocale(): Locale {
          return Locale::create(session('locale'));
      }
      
  5. Translation Key Generation

    function generateTranslationKey(string $locale, string $key): string {
        return sprintf('%s.%s', $locale->getLanguage(), $key);
    }
    

Advanced Patterns

  • Locale-Aware Validation

    $locale = Locale::create('de-DE');
    if ($locale->getRegion() === 'DE' && $locale->getScript() === 'Latn') {
        // Apply German-specific validation
    }
    
  • Fallback Locale Logic

    function resolveLocale(string $preferred): Locale {
        $fallbacks = ['en-US', 'en-GB', 'en'];
        foreach ($fallbacks as $fallback) {
            if (Locale::create($preferred)->equals(Locale::create($fallback))) {
                return Locale::create($fallback);
            }
        }
        return Locale::create('en');
    }
    

Gotchas and Tips

Common Pitfalls

  1. Invalid Locale Strings

    • Locale::create('invalid-locale') returns an invalid locale.
    • Always check isValid() before use:
      if (!$locale->isValid()) {
          throw new \InvalidArgumentException("Invalid locale: {$locale->getId()}");
      }
      
  2. Case Sensitivity

    • BCP 47 is case-insensitive, but the package normalizes to uppercase.
    • Avoid mixing en-us and en-US in your codebase.
  3. Script and Extension Handling

    • Scripts (e.g., Hans for simplified Chinese) and extensions (e.g., calendar=gregorian) are parsed but rarely used.
    • Example:
      $locale = Locale::create('zh-Hans-CN-u-ca-gregorian');
      echo $locale->getScript(); // "Hans"
      
  4. Performance with Many Locales

    • Parsing locales is lightweight, but cache Locale::create() results if reused:
      static $cachedLocales = [];
      $locale = $cachedLocales[$id] ?? Locale::create($id);
      

Debugging Tips

  • Inspect Locale Components

    $locale = Locale::create('es-MX-u-ca-gregorian');
    dump([
        'language' => $locale->getLanguage(),
        'region'   => $locale->getRegion(),
        'script'   => $locale->getScript(),
        'extensions' => $locale->getExtensions(),
    ]);
    
  • Compare Locales Use equals() with different comparison flags:

    $locale1 = Locale::create('en-US');
    $locale2 = Locale::create('en-us-u-ca-gregorian');
    $locale1->equals($locale2, Locale::COMPARE_LANGUAGE); // true
    $locale1->equals($locale2, Locale::COMPARE_ALL);      // false
    

Extension Points

  1. Custom Locale Validation Extend Locale to add business logic:

    class BusinessLocale extends Locale {
        public function isBusinessLocale(): bool {
            return $this->getRegion() === 'US' || $this->getRegion() === 'GB';
        }
    }
    
  2. Locale-Specific Logic Use getId() to dispatch logic:

    match ($locale->getId()) {
        'fr-FR' => $this->applyFrenchRules(),
        'de-DE' => $this->applyGermanRules(),
        default => $this->applyDefaultRules(),
    };
    
  3. Integration with Laravel's Localization Override Laravel's App::setLocale() to use yiisoft/i18n:

    use Yiisoft\I18n\Locale;
    
    App::setLocale(function () {
        $localeId = session('locale', 'en-US');
        return Locale::create($localeId)->getLanguage();
    });
    

Configuration Quirks

  • No Default Config The package is stateless; configure fallbacks or defaults in your app:

    config([
        'i18n' => [
            'default_locale' => 'en-US',
            'fallback_locales' => ['en-GB', 'en'],
        ],
    ]);
    
  • BCP 47 Compliance Stick to RFC standards to avoid edge cases (e.g., private-use tags like x-locale).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport