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

ao/translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies

    composer require ao/translation-bundle stof/doctrine-extensions-bundle
    
  2. Register Bundles Add to AppKernel.php:

    new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
    new AO\TranslationBundle\AOTranslationBundle(),
    
  3. Configure Translator In config.yml:

    framework:
        translator: ~
    parameters:
        translator.class: AO\TranslationBundle\Translation\Translator
    ao_translation:
        locales:
            en: ~
            de: { label: "German" }
    
  4. Enable Timestampable Behavior

    stof_doctrine_extensions:
        orm:
            default:
                timestampable: true
    
  5. Update Schema

    php bin/console doctrine:schema:update --force
    
  6. Add Routing In routing.yml:

    ao_translation:
        resource: "@AOTranslationBundle/Controller/"
        type: annotation
        prefix: /
    

First Use Case

Use translations in a controller:

$this->get('translator')->trans('welcome.message', ['%name%' => 'John']);

Access the Translations Panel via Symfony Profiler (Debug Toolbar) to edit translations dynamically.


Implementation Patterns

Core Workflow

  1. Translation Usage Replace static strings with trans() calls:

    $this->get('translator')->trans('user.greeting', ['%username%' => $user->name]);
    
    • Lazy Loading: Only translations used in the current request are loaded from the DB.
  2. Editing Translations

    • Profiler Panel: Edit translations on-the-fly via the Debug Toolbar (no need to restart the server).
    • SonataAdmin Backend (optional): Install SonataAdminBundle and expose translations via /admin/ao/translation/message/list.
  3. Caching

    • Action Cache: Tracks which translations are used per route. Clear stale entries with:
      php bin/console ao:translation:clear-cache
      
    • Manual Reset: Use the "Reset action cache" button in the Profiler panel for the current action.

Integration Tips

  • Locale-Specific Labels Configure labels in ao_translation.locales for dropdowns in the GUI:

    ao_translation:
        locales:
            en: ~
            de: { label: "Deutsch" }  # Custom label
    
  • Separate Database for Translations Use a dedicated connection for shared environments (e.g., multi-developer teams):

    ao_translation:
        entity_manager: translations
    

    Run schema updates with:

    php bin/console doctrine:schema:update --em=translations
    
  • Fallback Locales Define fallback chains in config.yml:

    framework:
        translator:
            fallbacks:
                de: en
    
  • Translation Domains Group translations by domain (e.g., admin, frontend):

    $this->get('translator')->trans('admin.dashboard.title', [], 'admin');
    

Gotchas and Tips

Pitfalls

  1. Cache Staleness

    • Issue: Deleted translations may persist in the Profiler panel until the cache is reset.
    • Fix: Click "Reset cache" in the Profiler or run:
      php bin/console ao:translation:clear-cache
      
  2. Missing Timestampable Behavior

    • Issue: If stof_doctrine_extensions is misconfigured, translations won’t update timestamps.
    • Fix: Ensure timestampable: true is set for the correct entity manager.
  3. Profiler Panel Not Showing

    • Issue: The Translations tab may not appear if the bundle isn’t properly registered or the Profiler is disabled.
    • Fix: Verify AOTranslationBundle is in AppKernel and the Profiler is enabled in dev environment.
  4. SonataAdmin Dependency

    • Issue: The backend requires SonataAdminBundle but isn’t documented clearly.
    • Fix: Install and configure Sonata bundles before using the backend:
      composer require sonata-project/admin-bundle sonata-project/doctrine-orm-admin-bundle
      
  5. Locale Configuration Overrides

    • Issue: Custom locale labels may not reflect in the GUI if the config isn’t reloaded.
    • Fix: Clear the cache after updating ao_translation.locales:
      php bin/console cache:clear
      

Debugging Tips

  • Check Translations Table Inspect ao_translation_message in your DB to verify entries:

    SELECT * FROM ao_translation_message WHERE domain = 'messages';
    
  • Enable SQL Logging Debug Doctrine queries in config.yml:

    doctrine:
        dbal:
            logging: true
    
  • Log Translator Events Add a listener to track translation calls:

    // src/AO/TranslationBundle/EventListener/TranslationListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        if ($request->hasPreviousSession()) {
            $this->logger->info('Translations used:', [
                'domain' => $request->attributes->get('_route_params'),
            ]);
        }
    }
    

Extension Points

  1. Custom Translation Providers Extend the bundle’s Translator class to add logic (e.g., API-based fallbacks):

    class CustomTranslator extends AO\TranslationBundle\Translation\Translator {
        public function getTranslation($id, $locale, $domain = null) {
            // Add custom logic (e.g., check API first)
            return parent::getTranslation($id, $locale, $domain);
        }
    }
    

    Register in config.yml:

    parameters:
        translator.class: AppBundle\Translation\CustomTranslator
    
  2. Override Templates Customize the Profiler panel or SonataAdmin templates by overriding:

    src/AO/TranslationBundle/Resources/views/
    
  3. Add Validation Rules Extend the Message entity to validate translations (e.g., max length):

    // src/AO/TranslationBundle/Entity/Message.php
    /**
     * @Assert\Length(max=255)
     */
    private $message;
    
  4. Event Subscribers Hook into translation events (e.g., log changes):

    // src/AO/TranslationBundle/EventListener/TranslationSubscriber.php
    public static function getSubscribedEvents() {
        return [
            AOTranslationEvents::PRE_TRANSLATION_SAVE => 'onPreTranslationSave',
        ];
    }
    
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