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

Translator Bundle Laravel Package

danilovl/translator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require danilovl/translator-bundle
    

    Ensure TranslatorBundle is enabled in config/bundles.php (auto-detected in Symfony 5.1+).

  2. Configuration Publish the default config:

    php bin/console translator:install
    

    This creates:

    • Database table (translations)
    • Default YAML structure (config/translations/)
  3. First Use Case Translate a string in a controller:

    use TranslatorBundle\Service\TranslationService;
    
    class MyController extends AbstractController {
        public function index(TranslationService $translator): Response {
            $translation = $translator->get('messages.welcome');
            return $this->render('index.html.twig', ['message' => $translation]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. YAML-to-Database Sync

    php bin/console translator:sync:yaml-to-db
    
    • Use this after updating YAML files to push changes to the database.
    • Ideal for CI/CD pipelines or pre-deployment.
  2. Database-to-YAML Sync

    php bin/console translator:sync:db-to-yaml
    
    • Sync live database changes back to YAML (e.g., for EasyAdmin edits).
    • Run manually or via a post-save event listener.
  3. Cache Management

    php bin/console translator:cache:generate
    
    • Generate cached translations (e.g., after bulk updates).
    • Automatically triggered via EasyAdmin’s onAfterUpdate event.

Integration Tips

  • Twig Integration Extend the default translator service to work with Twig:

    {{ app.translator.get('messages.welcome', { name: user.name }) }}
    

    (Requires binding the service in services.yaml:

    services:
        App\Twig\TranslationExtension:
            tags: ['twig.extension']
            arguments: ['@translator']
    
  • EasyAdmin CRUD Use the provided TranslationCrudController:

    use TranslatorBundle\Controller\TranslationCrudController;
    
    class TranslationController extends TranslationCrudController { ... }
    
    • Auto-registers routes under /admin/translations.
    • Supports bulk updates and real-time cache refresh.
  • Dynamic Namespaces Override the default namespace (messages) in config/packages/translator.yaml:

    translator:
        default_namespace: 'app'
        yaml_directory: '%kernel.project_dir%/config/translations'
    

Gotchas and Tips

Pitfalls

  1. Namespace Collisions

    • If YAML files share keys (e.g., messages.welcome in both messages.yml and auth.yml), the last synced file overwrites.
    • Fix: Use unique keys or merge YAML files manually.
  2. Cache Staleness

    • The cache isn’t invalidated automatically on YAML edits (only via sync:yaml-to-db or EasyAdmin).
    • Fix: Clear cache manually or add a post-update event listener:
      // src/EventListener/TranslationUpdateListener.php
      use Symfony\Component\HttpKernel\Event\PostResponseEvent;
      use TranslatorBundle\Service\TranslationService;
      
      class TranslationUpdateListener {
          public function __construct(private TranslationService $translator) {}
      
          public function onPostUpdate(PostResponseEvent $event): void {
              $this->translator->clearCache();
          }
      }
      
  3. EasyAdmin Permissions

    • The bundled CRUD requires ROLE_ADMIN. Ensure your security.yaml includes:
      access_control:
          - { path: ^/admin/translations, roles: ROLE_ADMIN }
      

Debugging

  • Check Sync Status

    php bin/console translator:status
    
    • Lists pending YAML/DB changes.
  • Log Translation Lookups Enable debug mode in translator.yaml:

    translator:
        debug: true
    
    • Logs missed translations to var/log/dev.log.

Extension Points

  1. Custom Storage Override the default TranslationStorage service to support JSON or XML:

    # config/services.yaml
    TranslatorBundle\Storage\TranslationStorage:
        arguments:
            $connection: '@doctrine.dbal.default_connection'
            $table: 'custom_translations'
    
  2. Pre-Translation Hooks Add a subscriber to validate translations before sync:

    use TranslatorBundle\Event\TranslationEvent;
    
    class TranslationValidatorSubscriber {
        public function onPreSync(TranslationEvent $event): void {
            $translations = $event->getTranslations();
            // Validate $translations here (e.g., check for empty values).
        }
    }
    

    Register in services.yaml:

    services:
        App\EventSubscriber\TranslationValidatorSubscriber:
            tags: ['kernel.event_subscriber']
    
  3. Multi-Database Support For multi-tenancy, extend the storage to use a tenant-aware connection:

    class TenantTranslationStorage extends TranslationStorage {
        public function __construct(private TenantConnection $connection) {}
    
        public function findAll(): array {
            return $this->connection->fetchAllAssociative('SELECT * FROM translations WHERE tenant_id = ?', [$this->tenantId]);
        }
    }
    
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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver