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

Json Translation Bundle Laravel Package

alexandre-fernandez/json-translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require alexandre-fernandez/json-translation-bundle
    

    Enable the bundle in config/bundles.php:

    AlexandreFernandez\JsonTranslationBundle\AlexandreFernandezJsonTranslationBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference AlexandreFernandezJsonTranslationBundle
    

    Update config/packages/alexandre_fernandez_json_translation.yaml:

    alexandre_fernandez_json_translation:
        locales: ['en', 'fr', 'es']  # Your supported locales
        default_locale: 'en'         # Fallback locale
        storage: '%kernel.project_dir%/var/translations'  # JSON storage path
    
  3. First Use Case: Translating JSON Data Store translations in JSON files (e.g., var/translations/messages.en.json):

    {
        "welcome": "Welcome, {name}!",
        "error": {
            "not_found": "Resource not found"
        }
    }
    

    Use in a controller/service:

    use AlexandreFernandez\JsonTranslationBundle\Translator\JsonTranslator;
    
    class MyController extends AbstractController {
        public function showWelcome(JsonTranslator $translator) {
            $translation = $translator->trans('messages.welcome', ['%name%' => 'John']);
            return new Response($translation); // Outputs: "Welcome, John!"
        }
    }
    

Implementation Patterns

1. Translation Workflows

Dynamic JSON Loading

  • Use JsonTranslator to load translations on-demand:
    $translator->load('custom', 'path/to/custom.json');
    $translator->trans('custom.key');
    
  • Ideal for user-generated or app-specific translations.

Fallback Logic

  • Configure fallback locales in config:
    alexandre_fernandez_json_translation:
        fallback_locales: ['en', 'fr']
    
  • Automatically falls back if a translation is missing in the requested locale.

Namespacing

  • Organize translations hierarchically:
    var/translations/
    ├── messages.en.json
    ├── validation.fr.json
    └── errors.es.json
    
  • Reference with dot notation:
    $translator->trans('validation.email.required');
    

2. Integration with Laravel

Service Provider Binding

Bind the translator to Laravel’s container in AppServiceProvider:

public function register() {
    $this->app->singleton(JsonTranslator::class, function ($app) {
        return new JsonTranslator(
            $app['kernel']->getProjectDir() . '/var/translations',
            ['en', 'fr'],
            'en'
        );
    });
}

Blade Directives

Create a custom Blade directive for translations:

Blade::directive('jsontrans', function ($expression) {
    return "<?php echo app('AlexandreFernandez\\JsonTranslationBundle\\Translator\\JsonTranslator')->trans({$expression}); ?>";
});

Usage in Blade:

<h1>{{ jsontrans('messages.welcome', ['%name%' => $user->name]) }}</h1>

Validation Messages

Override Symfony’s validator translations:

# config/validator/translation_mappings.yaml
AlexandreFernandezJsonTranslationBundle:
    resource: "@AlexandreFernandezJsonTranslationBundle/Resources/translations/validator"
    type: "json"
    prefix: "validator"

Store custom validation rules in var/translations/validation.{locale}.json:

{
    "constraints": {
        "UniqueEntity": "This value is already used."
    }
}

3. CLI Utilities

Dump Translations

Generate JSON files from existing translations (e.g., Symfony’s translations directory):

php bin/console alexandre-fernandez:json-translation:dump

Outputs JSON files in var/translations/.

Validate JSON

Check for syntax errors in translation files:

php bin/console alexandre-fernandez:json-translation:validate

Gotchas and Tips

Pitfalls

  1. Caching Issues

    • JSON files are not auto-reloaded. Clear cache after updates:
      php bin/console cache:clear
      
    • For development, disable caching in config:
      alexandre_fernandez_json_translation:
          cache: false
      
  2. Locale-Specific Paths

    • Ensure all locales have matching JSON files (e.g., messages.en.json and messages.fr.json). Missing files will trigger fallback or errors.
  3. Variable Interpolation

    • Use %placeholder% syntax (not {placeholder}) for variable replacement:
      { "greeting": "Hello, %name%!" }  // Correct
      { "greeting": "Hello, {name}!" }   // Fails silently
      
  4. File Permissions

    • Ensure var/translations/ is writable by the web server:
      chmod -R 775 var/translations/
      

Debugging Tips

  1. Check Loaded Translations Dump the translator’s loaded files:

    $translator->getLoadedFiles(); // Returns array of loaded JSON paths
    
  2. Enable Debug Mode Log missing translations to var/log/dev.log:

    alexandre_fernandez_json_translation:
        debug: true
    
  3. Validate JSON Manually Use jsonlint.com to verify syntax in translation files.


Extension Points

  1. Custom Storage Extend AlexandreFernandez\JsonTranslationBundle\Storage\JsonStorage to support remote storage (e.g., S3):

    class S3JsonStorage extends JsonStorage {
        public function read($locale, $namespace) {
            // Implement S3 logic
        }
    }
    
  2. Translation Providers Add dynamic providers (e.g., database-backed translations):

    $translator->addProvider(new DatabaseTranslationProvider());
    
  3. Event Listeners Listen for translation events (e.g., TranslationNotFoundEvent):

    $eventDispatcher->addListener(
        TranslationNotFoundEvent::class,
        function (TranslationNotFoundEvent $event) {
            // Fallback logic or logging
        }
    );
    

Performance Optimization

  1. Preload Translations Load frequently used translations in a service constructor:

    public function __construct(JsonTranslator $translator) {
        $translator->load('messages', 'path/to/messages');
        $translator->load('validation', 'path/to/validation');
    }
    
  2. Combine JSON Files Merge small JSON files into larger ones to reduce I/O operations:

    // Before (multiple files)
    messages.en.json, validation.en.json
    
    // After (combined)
    translations.en.json
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours