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

Translationbundle Laravel Package

connectsb/translationbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require connectsb/translationbundle:dev-master
    

    Add to AppKernel.php:

    new ConnectSB\TranslationBundle\ConnectSBTranslationBundle(),
    
  2. Configure config.yml:

    connect_sb_translation:
        database_translations_domain: "app"  # Your translation domain (e.g., "app", "validation")
        database_translations_entity: "Translation"  # Your entity name (plural)
    
  3. Extend Base Entities: Create TranslationKey and TranslationValue extending BaseTranslationKey/BaseTranslationValue (see README example). Define relationships to your domain entity (e.g., @ORM\ManyToOne(targetEntity="YourEntity")).

  4. First Use Case:

    • Fetch a translation:
      $translator = $this->get('translator');
      $translator->trans('your.key', [], 'app'); // Uses DB-backed translations
      
    • Edit translations via admin panel: The bundle provides a UI to manage translations (check Resources/config/routing.yml for routes).

Implementation Patterns

Workflows

  1. Translation Management:

    • Admin UI: Use the built-in CRUD interface to add/edit translations for specific locales.
    • Entity-Coupled Translations: Link translations to entities (e.g., a Product entity’s translations are stored in TranslationKey/TranslationValue tied to the Product via a relationship).
  2. Integration with Symfony Translator:

    • Override the default translator service to prioritize database translations:
      # services.yml
      translator:
          class: Symfony\Component\Translation\Translator
          arguments:
              - "%kernel.default_locale%"
              - { path: "%kernel.root_dir%/Resources/translations" }  # Fallback to YAML/JSON
              - { db: true }  # Custom argument to enable DB lookup
      
    • Create a custom Loader to fetch translations from the database:
      // src/ConnectSB/TranslationBundle/Loader/DatabaseLoader.php
      class DatabaseLoader extends Loader {
          public function load($resource, $locale, $domain = null) {
              // Query TranslationValue for the domain/locale and return as array
          }
      }
      
  3. Localization Workflow:

    • Add a translation:
      1. Create a TranslationKey (e.g., product.name).
      2. Add TranslationValue entries for each locale (e.g., en: "Product Name", fr: "Nom du Produit").
      3. Link to your entity via the relationship field (e.g., product_id).
    • Fallback Chain: Configure the translator to fall back to YAML/JSON if the key is missing in the database.
  4. Entity-Specific Translations:

    • Useful for dynamic content (e.g., CMS pages, user-generated content). Example:
      // In your entity (e.g., Product)
      /**
       * @ORM\OneToMany(targetEntity="TranslationKey", mappedBy="product")
       */
      private $translations;
      

Gotchas and Tips

Pitfalls

  1. Outdated Bundle:

    • Last release in 2015; test thoroughly. Potential issues with Symfony 4/5/6 compatibility (e.g., Doctrine ORM changes, Twig syntax).
    • Fix: Override deprecated methods or use a compatibility layer (e.g., symfony/translation v4+).
  2. Configuration Quirks:

    • database_translations_domain cannot be "messages" (reserved by Symfony). Use "app" or a custom domain.
    • Tip: Validate the database_translations_entity name matches your extended entity (plural form).
  3. Performance:

    • Database lookups add latency. Cache translations aggressively:
      // Cache the loaded translations for 1 hour
      $cache = $this->get('translator.data_collector')->getTranslationCache();
      $cache->set('app', $translations, 3600);
      
  4. Admin UI Limitations:

    • The built-in admin panel is basic. Extend it with custom Twig templates or use EasyAdmin for a modern UI.
    • Example: Override Resources/views/Translation/key/edit.html.twig.
  5. Migration Risks:

    • Changing TranslationKey/TranslationValue after initial setup may break existing data. Use Doctrine migrations carefully.

Debugging Tips

  1. Missing Translations:

    • Check if the TranslationValue exists for the locale/domain. Enable SQL logging:
      doctrine:
          dbal:
              logging: true
      
    • Verify the translator’s fallback chain in config.yml:
      framework:
          translator:
              fallbacks:
                  - "%locale%"
      
  2. Entity Relationships:

    • If translations aren’t linking to your entity, ensure:
      • The mappedBy/inversedBy in your entity matches the relationship in TranslationKey.
      • The product_id (or similar) field is populated when saving.
  3. Locale-Specific Issues:

    • Test all target locales. The bundle doesn’t auto-create locales; add them manually via TranslationValue.

Extension Points

  1. Custom Validation:

    • Add validation to TranslationKey/TranslationValue (e.g., unique keys per domain):
      /**
       * @Assert\Unique(entityManager="doctrine.orm.entity_manager", fields="domain", message="Key already exists.")
       */
      private $key;
      
  2. Event Listeners:

    • Trigger actions on translation updates (e.g., clear cache):
      // src/EventListener/TranslationListener.php
      class TranslationListener {
          public function onTranslationUpdate(TranslationEvent $event) {
              $this->get('cache')->clear('translations');
          }
      }
      
      Register in services.yml:
      services:
          app.translation_listener:
              class: AppBundle\EventListener\TranslationListener
              tags:
                  - { name: kernel.event_listener, event: translation.update, method: onTranslationUpdate }
      
  3. API Endpoints:

    • Expose translations via API for frontend use:
      // src/Controller/TranslationController.php
      class TranslationController extends Controller {
          public function getTranslationsAction($domain, $locale) {
              return $this->getDoctrine()->getRepository('ConnectSBTranslationBundle:TranslationValue')
                  ->findByDomainAndLocale($domain, $locale);
          }
      }
      
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.
terminal42/code-quality-tools
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