Weave 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

Translation Definitions Laravel Package

weglot/translation-definitions

Laravel package providing translation definitions for Weglot integrations—helpers and configuration to manage translation keys, mapping, and defaults in a consistent way across your app. Useful for standardizing multilingual content handling with Weglot.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require weglot/translation-definitions
    

    This installs the shared translation definitions without requiring additional setup.

  2. Publish Configuration (Optional) If the package includes default configurations or assets, publish them:

    php artisan vendor:publish --tag=weglot-translation-definitions
    

    This generates a config/weglot-translation-definitions.php file for customization.

  3. First Use Case: Define a Translation Key Use the package’s interfaces or value objects to define a translation key. For example:

    use Weglot\TranslationDefinitions\Language;
    use Weglot\TranslationDefinitions\TranslationKey;
    
    $key = new TranslationKey('user.welcome', [
        'en' => 'Welcome, {name}!',
        'es' => '¡Bienvenido, {name}!',
    ]);
    
    // Store or use the key in your application logic.
    
  4. Integrate with Laravel’s Translation System If using Laravel’s built-in translation system, extend the package’s definitions:

    // In a service provider or config file
    'translations' => [
        'paths' => [
            resource_path('lang/weglot'),
        ],
    ],
    

    Place Weglot-compatible translation files in resources/lang/weglot.


Implementation Patterns

Usage Patterns

  1. Defining Translation Keys Use the package’s TranslationKey or TranslationDefinition classes to structure translations:

    $definition = new TranslationDefinition(
        'user.profile',
        [
            'en' => 'Profile Settings',
            'fr' => 'Paramètres du profil',
        ],
        ['plural' => true] // Optional metadata
    );
    
  2. Language and Locale Handling Leverage the Language and Locale value objects for consistency:

    $language = new Language('en', 'English');
    $locale = new Locale('en_US', 'en', 'US');
    
  3. Integration with Laravel’s trans() Helper Ensure translations align with Laravel’s syntax:

    // In Blade or PHP
    {{ trans('weglot::user.welcome', ['name' => 'John']) }}
    

    Store Weglot-specific translations in resources/lang/vendor/weglot/.

  4. Service Provider Integration Bind the package’s interfaces to Laravel’s container for dependency injection:

    // In AppServiceProvider
    public function register()
    {
        $this->app->bind(
            TranslationDefinitionResolver::class,
            WeglotTranslationDefinitionResolver::class
        );
    }
    
  5. Dynamic Translation Loading For dynamic content (e.g., CMS-driven translations), use the package’s resolvers:

    $resolver = app(TranslationDefinitionResolver::class);
    $definition = $resolver->resolve('dynamic.key');
    

Workflows

  1. Translation Extraction Use the package’s tools to extract translation keys from your codebase:

    php artisan weglot:extract
    

    This generates a report of missing or unused keys.

  2. Translation Validation Validate translations against Weglot’s schema:

    php artisan weglot:validate
    

    Ensures keys and locales adhere to the package’s standards.

  3. Hybrid Translation Management Combine Weglot’s definitions with Laravel’s native translations:

    • Store Weglot-specific translations in resources/lang/vendor/weglot/.
    • Use Laravel’s lang directory for non-Weglot translations.
  4. Testing Translations Write PHPUnit tests to verify translations:

    public function testTranslationResolution()
    {
        $this->assertEquals(
            'Welcome, John!',
            trans('weglot::user.welcome', ['name' => 'John'])
        );
    }
    

Integration Tips

  1. Middleware for Language Detection Use Weglot’s middleware to detect and set the user’s preferred language:

    // In app/Http/Kernel.php
    protected $middlewareGroups = [
        'web' => [
            // ...
            \Weglot\TranslationDefinitions\Http\Middleware\DetectLanguage::class,
        ],
    ];
    
  2. Event Listeners for Translation Updates Listen for translation updates and trigger cache invalidation:

    // In EventServiceProvider
    protected $listen = [
        'weglot.translation.updated' => [
            \App\Listeners\InvalidateTranslationCache::class,
        ],
    ];
    
  3. Customizing Fallback Logic Extend the package’s fallback resolver to handle missing translations:

    public function resolve($key, $locale = null, $fallback = true)
    {
        $definition = $this->getDefinition($key, $locale);
        return $definition ?: ($fallback ? trans('fallback.' . $key) : null);
    }
    
  4. API Integration If using Weglot’s API, integrate the package’s definitions with API responses:

    $translations = $this->weglotApi->fetchTranslations($locale);
    $this->translationStore->store($translations);
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Issue: Weglot’s translation keys may conflict with existing keys in resources/lang.
    • Fix: Use a unique namespace (e.g., weglot::user.welcome) and ensure Laravel’s translation loader respects it.
  2. Locale Mismatches

    • Issue: Weglot’s locales (e.g., en_US) may not align with Laravel’s App::getLocale() (e.g., en).
    • Fix: Normalize locales in a service provider:
      app()->bind('locale.normalizer', function () {
          return new WeglotLocaleNormalizer();
      });
      
  3. Performance Overhead

    • Issue: Dynamically resolving translations per request can slow down TTFB.
    • Fix: Cache resolved definitions:
      Cache::remember("weglot.definitions.{$locale}", now()->addHours(1), function () use ($locale) {
          return $this->resolver->resolveAll($locale);
      });
      
  4. Breaking Changes

    • Issue: Weglot may update their definitions without semantic versioning.
    • Fix: Use strict version constraints in composer.json:
      "weglot/translation-definitions": "^1.0"
      
      Monitor for deprecations in Weglot’s changelog.
  5. Missing Fallback Logic

    • Issue: Translations may fail silently if a key or locale is missing.
    • Fix: Implement a robust fallback chain:
      $translation = trans('weglot::key', [], $locale) ?: trans('fallback.key');
      

Debugging

  1. Log Translation Resolution Enable debug logging for translation issues:

    // In config/weglot-translation-definitions.php
    'debug' => env('APP_DEBUG', false),
    

    Check logs for Weglot\TranslationDefinitions\Logging\TranslationLogger.

  2. Inspect Resolved Definitions Dump definitions to debug missing keys:

    dd(app(TranslationDefinitionResolver::class)->resolve('missing.key'));
    
  3. Validate Translation Files Use Artisan commands to validate your translation files:

    php artisan weglot:validate --locale=es --path=resources/lang/vendor/weglot
    
  4. Check for Circular Dependencies If translations reference each other, use a dependency checker:

    composer require --dev nette/di
    php artisan weglot:check-circular-dependencies
    

Config Quirks

  1. Default Language Configuration Ensure config/app.php and Weglot’s config align:

    'locale' => 'en', // Laravel default
    'weglot' => [
        'default_locale' => 'en_US', // Weglot default
    ],
    
  2. Caching Configuration Configure caching for definitions:

    'cache' => [
        'enabled' => true,
        'driver' => 'file', // or 'redis', 'database'
        'ttl' => 60, // minutes
    ],
    
  3. Path Configuration Specify custom paths for translation files:

    'paths' => [
        'weglot' => resource_path('lang/vendor/weglot'),
        'fallback' => resource_path('lang/fallback'),
    ],
    

Extension Points

  1. Custom Value Objects Extend Weglot’s value objects for project-specific needs:

    class CustomTranslationKey extends TranslationKey
    {
        public function __construct(string $key, array $translations, array $metadata = [])
        {
            parent::__construct($key, $translations, $metadata + ['custom' => true]);
        }
    }
    
  2. Custom Resolvers Implement a custom resolver for non-standard translation

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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums