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

Translation Bundle Laravel Package

alessandrolandim/translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alessandrolandim/translation-bundle
    

    (Note: The package name in the composer.json differs from the GitHub repo. Use lexik/translation-bundle instead for compatibility with the documented version.)

  2. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        Lexik\TranslationBundle\LexikTranslationBundle::class => ['all' => true],
    ];
    
  3. Configure Database Storage Update config/packages/lexik_translation.yaml (auto-generated):

    lexik_translation:
        driver: doctrine
        doctrine:
            entity_manager: default
            class: App\Entity\Translation
    
  4. Create Translation Entity Generate the entity (if not using auto-generation):

    php bin/console make:entity Translation
    

    (Follow documentation for fields: locale, domain, id, message, messageId.)

  5. Import Initial Translations

    php bin/console lexik:translation:import --format=yml --dir=%kernel.project_dir%/translations
    
  6. Access the GUI Visit /translation (or /admin/translation if using Symfony AdminBundle).


First Use Case: Localization Override

  1. Edit a Translation Navigate to the GUI, search for validation.required in the messages domain, and override the default YAML value (e.g., "This value should not be blank.""Campo obrigatório.").

  2. Verify in Code

    $this->get('translator')->trans('validation.required', [], 'messages');
    

    (Returns the overridden value.)


Implementation Patterns

Workflow: Managing Translations

  1. Development Phase

    • Store translations in YAML/JSON/XLiff files (e.g., translations/messages.en.yml).
    • Use the CLI to import:
      php bin/console lexik:translation:import --format=yml --dir=translations
      
  2. Production Phase

    • Edit translations via the GUI (/translation).
    • Export to files (for backup or sharing):
      php bin/console lexik:translation:export --format=yml --dir=translations
      
  3. Collaboration

    • Use the GUI’s "Compare" feature to track changes between locales.
    • Assign translations to teams via Symfony’s security roles (e.g., ROLE_TRANSLATOR).

Integration Tips

  1. Custom Domains Extend the entity to support custom domains (e.g., email_templates):

    // config/packages/lexik_translation.yaml
    lexik_translation:
        domains:
            - messages
            - email_templates
    
  2. Validation Rules Add constraints to the Translation entity:

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\NotBlank
     * @Assert\Length(max=255)
     */
    private $message;
    
  3. Event Listeners Log translation changes:

    // src/EventListener/TranslationListener.php
    public function onTranslationUpdate(TranslationEvent $event) {
        \Log::info('Translation updated', [
            'locale' => $event->getTranslation()->getLocale(),
            'domain' => $event->getTranslation()->getDomain(),
        ]);
    }
    

    Register in services.yaml:

    services:
        App\EventListener\TranslationListener:
            tags:
                - { name: kernel.event_listener, event: lexik.translation.pre_update }
    
  4. API Access Expose translations via API (e.g., using API Platform):

    # config/api_platform/resources.yaml
    resources:
        App\Entity\Translation:
            collectionOperations:
                get:
                    method: GET
                    path: /api/translations
                    normalization_context:
                        groups: ['translation:read']
    

Advanced: Dynamic Locale Switching

  1. Middleware for Locale Routing

    // src/EventListener/LocaleListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        $locale = $request->get('locale', 'en');
        $event->getRequest()->setLocale($locale);
    }
    

    Register:

    services:
        App\EventListener\LocaleListener:
            tags:
                - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
    
  2. Database-First Translations Override the translator to prioritize database entries:

    # config/packages/translation.yaml
    framework:
        translator:
            paths:
                - '%kernel.project_dir%/translations'
            defaults:
                locale: '%locale%'
            lexik_translation:
                database_loader: true
    

Gotchas and Tips

Pitfalls

  1. Entity Mismatch

    • Issue: The bundle expects a Translation entity with specific fields (locale, domain, messageId, message).
    • Fix: Regenerate the entity if fields are missing:
      php bin/console make:entity Translation --regenerate
      
  2. CLI Import Failures

    • Issue: lexik:translation:import fails with "No translation files found."
    • Fix: Ensure files are in the correct format (e.g., messages.en.yml) and the --dir path is absolute or relative to the project root.
  3. Caching Conflicts

    • Issue: Translations don’t update after GUI changes.
    • Fix: Clear the translator cache:
      php bin/console cache:clear
      
    • Pro Tip: Disable cache for development:
      # config/packages/translation.yaml
      framework:
          translator:
              caching: false
      
  4. Locale-Specific Routes

    • Issue: Routes like /translation ignore the current locale.
    • Fix: Use the locale parameter:
      /translation?locale=es
      

Debugging

  1. Check DatabaseLoader Verify the DatabaseLoader is registered:

    php bin/console debug:container lexik.translation.database_loader
    

    (Should return Lexik\TranslationBundle\Loader\DatabaseLoader.)

  2. SQL Queries Enable Doctrine debugging:

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    

    (Check var/log/dev.log for queries like SELECT message FROM translation WHERE messageId = ? AND locale = ?.)

  3. Event Dispatching Debug events with:

    php bin/console debug:event-dispatcher
    

    (Look for lexik.translation.pre_update, lexik.translation.post_update.)


Extension Points

  1. Custom Importers Extend the importer to support custom formats (e.g., CSV):

    // src/Importer/CsvImporter.php
    use Lexik\TranslationBundle\Importer\ImporterInterface;
    
    class CsvImporter implements ImporterInterface {
        public function import(string $file, string $locale, string $domain): void {
            // Parse CSV and save to database
        }
    }
    

    Register in services.yaml:

    services:
        App\Importer\CsvImporter:
            tags:
                - { name: lexik_translation.importer, format: csv }
    
  2. GUI Customization Override the Twig templates:

    mkdir -p templates/bundles/LexikTranslationBundle
    cp vendor/lexik/translation-bundle/Resources/views/* templates/bundles/LexikTranslationBundle/
    

    (Edit edit.html.twig to add custom fields or buttons.)

  3. Translation Approval Workflow Add a status field to the Translation entity and filter the GUI:

    // src/Entity/Translation.php
    private $status = 'draft'; // draft | reviewed | published
    
    // Filter in the bundle's repository
    public function findUnreviewed(string $locale) {
        return $this->createQueryBuilder('t')
            ->where('t.locale = :locale')
            ->andWhere('t.status = :status')
            ->setParameter('locale', $locale)
            ->setParameter('status', 'draft')
            ->getQuery()
            ->getResult();
    }
    

Configuration Quirks

  1. Doctrine vs. MongoDB
    • The bundle supports both Doctrine ORM and MongoDB ODM.
    • ORM: Use Lexik\TranslationBundle\Entity\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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware