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 Bundle Laravel Package

cyberspectrum/i18n-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cyberspectrum/i18n-bundle
    

    Add to config/bundles.php (Symfony) or config/app.php (Laravel via bridge):

    Cyberspectrum\I18nBundle\CyberspectrumI18nBundle::class => ['all' => true],
    
  2. Configuration: Publish the default config:

    php artisan vendor:publish --provider="Cyberspectrum\I18nBundle\CyberspectrumI18nBundle" --tag="config"
    

    Update config/i18n.php with your locales (e.g., ['en', 'fr']) and translation paths.

  3. First Use Case: Load translations in a controller/service:

    use Cyberspectrum\I18nBundle\I18n;
    
    class MyController extends Controller {
        public function __construct(private I18n $i18n) {}
    
        public function index() {
            $translation = $this->i18n->get('messages.welcome', [], 'en');
            return response()->json(['message' => $translation]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Translation Loading:

    • Static Key Access:
      $this->i18n->get('key.nested.subkey', ['param' => 'value']);
      
    • Dynamic Locale Switching:
      $this->i18n->setLocale('fr');
      $translation = $this->i18n->get('messages.error');
      
  2. File-Based Translations:

    • Store translations in resources/lang/{locale}/messages.php (Laravel-style) or translations/{locale}/messages.yml (Symfony-style).
    • Example messages.yml:
      welcome: "Welcome, {name}!"
      error: "An error occurred: {code}"
      
  3. Integration with Blade (Laravel):

    • Extend Blade directives:
      Blade::directive('trans', function ($expression) {
          return "<?php echo app('i18n')->get($expression); ?>";
      });
      
    • Usage:
      @trans('messages.welcome', ['name' => $user->name])
      
  4. Fallback Locales:

    • Configure in config/i18n.php:
      'fallback_locales' => ['en', 'fr'],
      
    • Automatically falls back if a translation is missing.
  5. Validation Messages:

    • Override Laravel/Symfony validation messages:
      $validator = Validator::make($data, $rules);
      $validator->setTranslator($this->i18n);
      

Gotchas and Tips

Pitfalls

  1. Locale Auto-Detection:

    • The bundle does not auto-detect locale by default. Manually set it:
      $this->i18n->setLocale(request()->header('Accept-Language') ?? 'en');
      
  2. Caching:

    • Translations are not cached by default. Enable caching in config/i18n.php:
      'cache' => [
          'enabled' => true,
          'driver' => 'file', // or 'redis', 'database'
      ],
      
    • Clear cache after updates:
      php artisan cache:clear
      
  3. File Format Conflicts:

    • The bundle expects YAML files by default. For JSON/Laravel PHP arrays:
      $this->i18n->setLoader(new \Cyberspectrum\I18nBundle\Loader\JsonLoader());
      
  4. Namespace Collisions:

    • Avoid duplicate keys across locales. Use unique prefixes (e.g., auth.login, auth.register).
  5. Service Container Binding:

    • If using Laravel, bind the service manually in AppServiceProvider:
      $this->app->bind(I18n::class, function ($app) {
          return new I18n($app['config']['i18n']);
      });
      

Debugging Tips

  1. Missing Translations:

    • Check storage/logs/laravel.log for TranslationNotFoundException.
    • Verify file paths in config/i18n.php:
      'paths' => [
          resource_path('lang/{locale}'),
      ],
      
  2. Locale Overrides:

    • Temporarily disable fallback to debug:
      $this->i18n->setFallbackLocales([]);
      
  3. Performance:

    • Profile translation loading with:
      $start = microtime(true);
      $this->i18n->get('key');
      $time = microtime(true) - $start;
      

Extension Points

  1. Custom Loaders:

    • Implement Cyberspectrum\I18nBundle\Loader\LoaderInterface for databases/APIs:
      class ApiLoader implements LoaderInterface {
          public function load($locale, $domain, $theme = null) {
              return json_decode(file_get_contents("https://api.example.com/translations/{$locale}"));
          }
      }
      
  2. Event Listeners:

    • Extend translation logic via events (e.g., TranslationLoaded):
      $this->i18n->addListener(function ($event) {
          if ($event->getKey() === 'messages.welcome') {
              $event->setTranslation(strtoupper($event->getTranslation()));
          }
      });
      
  3. Middleware for Locale:

    • Set locale per request in Laravel:
      public function handle($request, Closure $next) {
          $locale = $request->segment(1) ?? config('app.locale');
          app('i18n')->setLocale($locale);
          return $next($request);
      }
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor