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

Symfony Db I18N Bundle Laravel Package

creative/symfony-db-i18n-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require creative/symfony-db-i18n-bundle
    

    Add to config/bundles.php:

    Creative\DbI18nBundle\DbI18nBundle::class => ['all' => true],
    
  2. Configure Locales Define supported locales in config/services.yaml:

    parameters:
      locales: ['en', 'fr', 'de']
    
  3. Update Database Schema Run:

    php bin/console doctrine:schema:update --force
    

    (or create a custom migration if preferred)

  4. First Translation Usage In Twig templates, set the default domain:

    {% trans_default_domain 'db_messages' %}
    

    Then use translations as usual:

    {{ 'welcome.message'|trans }}
    

First Use Case: Adding a Translation via Admin Panel

  1. Create a CRUD Controller/Interface Use Symfony’s make:crud or manually scaffold a controller for Translation entity (auto-generated by the bundle). Example route:

    # config/routes.yaml
    translation:
      resource: 'translation'
      type: 'simple'
      path: '/admin/translations'
    
  2. Seed Initial Messages Import existing .po/.yml files into the database:

    php bin/console db:i18n:import
    

Implementation Patterns

Core Workflow: Managing Translations

  1. Database Structure The bundle creates a translation table with columns:

    • domain (e.g., db_messages)
    • locale (e.g., en, fr)
    • message_id (e.g., welcome.message)
    • message (translated string)
  2. Integration with Translator The bundle hooks into Symfony’s TranslatorInterface. Messages from the database take precedence over files. Example service override (if needed):

    # config/services.yaml
    services:
      Symfony\Contracts\Translation\TranslatorInterface:
        alias: 'creative.db_i18n.translator'
    
  3. Dynamic Locale Switching Use middleware or a listener to set the locale from the request:

    // src/EventListener/LocaleListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        $locale = $request->getPreferredLanguage(['en', 'fr']);
        $this->translator->setLocale($locale);
    }
    
  4. Batch Updates For bulk imports/updates, use the console command:

    php bin/console db:i18n:import --file=messages.en.yml
    

Advanced Patterns

  1. Custom Validation Extend the Translation entity to add validation (e.g., max length):

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\Length(max=255)
     */
    private $message;
    
  2. Translation Events Listen for translation.pre_save or translation.post_update events to log changes or notify admins:

    // src/EventSubscriber/TranslationSubscriber.php
    public static function getSubscribedEvents() {
        return [
            'translation.pre_save' => 'onPreSave',
        ];
    }
    
  3. Fallback Logic Configure fallback locales in db_i18n.yaml:

    fallback_locales:
      fr: en
      de: en
    
  4. API-Friendly Endpoints Expose translations via API for frontend apps:

    # config/routes.yaml
    api_translations:
      path: /api/translations/{locale}
      controller: App\Controller\TranslationController::getTranslations
      methods: GET
    

Gotchas and Tips

Pitfalls

  1. Locale Mismatch Errors

    • Issue: InvalidArgumentException if locales parameter is missing or misconfigured.
    • Fix: Ensure locales is defined in services.yaml and matches the database entries.
  2. Schema Updates

    • Issue: Forgetting to run doctrine:schema:update after installation.
    • Fix: Always update the schema or create a migration. The bundle does not auto-migrate.
  3. Caching Headaches

    • Issue: Translations not updating immediately due to Symfony’s translation cache.
    • Fix: Clear the cache after bulk updates:
      php bin/console cache:clear
      
  4. Domain Conflicts

    • Issue: Messages with the same message_id but different domain may overlap.
    • Fix: Use distinct domains (e.g., auth, validation) and set trans_default_domain per template.
  5. Character Encoding

    • Issue: Special characters (e.g., é, ü) may corrupt in the database.
    • Fix: Ensure your database connection uses utf8mb4:
      # config/packages/doctrine.yaml
      doctrine:
        dbal:
          charset: utf8mb4
      

Debugging Tips

  1. Check Database Contents Verify translations exist:

    SELECT * FROM translation WHERE locale = 'en' AND domain = 'db_messages';
    
  2. Enable Debug Mode Temporarily set APP_DEBUG=true in .env to see detailed translation errors.

  3. Log Translator Calls Override the translator to log which messages are being fetched:

    public function trans($id, array $parameters = [], $domain = null, $locale = null) {
        error_log("Translating: {$id}, Domain: {$domain}, Locale: {$locale}");
        return parent::trans($id, $parameters, $domain, $locale);
    }
    
  4. Console Command Debugging Use --verbose flag for console commands:

    php bin/console db:i18n:import --verbose
    

Extension Points

  1. Custom Storage Override the default TranslationRepository to add logic (e.g., soft deletes):

    // src/Repository/CustomTranslationRepository.php
    class CustomTranslationRepository extends TranslationRepository {
        public function remove(Translation $translation) {
            $translation->setIsDeleted(true);
            $this->getEntityManager()->flush();
        }
    }
    
  2. Custom Importer Extend the ImportCommand to support additional file formats (e.g., JSON):

    // src/Command/CustomImportCommand.php
    class CustomImportCommand extends ImportCommand {
        protected function parseFile(string $file): array {
            // Custom logic for JSON/other formats
        }
    }
    
  3. Translation API Build a GraphQL or REST API layer on top of the Translation entity for headless CMS use cases.

  4. Webhook Notifications Trigger webhooks on translation updates via event listeners for real-time sync with other services.

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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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