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

chamber-orchestra/translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chamber-orchestra/translation-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        ChamberOrchestra\TranslationBundle\TranslationBundle::class => ['all' => true],
    ];
    
  2. Configuration: Publish the default config:

    php bin/console chamber-orchestra:translation:install
    

    Edit config/packages/chamber_orchestra_translation.yaml to define your translation sources (e.g., google, deepL).

  3. First Use Case: Translate text via a service:

    use ChamberOrchestra\TranslationBundle\Service\TranslationService;
    
    $translator = $this->container->get(TranslationService::class);
    $result = $translator->translate('Hello', 'en', 'es');
    

Key Directories to Explore

  • DependencyInjection/: For config and extension logic.
  • Service/: Core translation services (e.g., TranslationService, Provider/GoogleProvider).
  • Exception/: Handle errors like TranslationException or ProviderException.

Implementation Patterns

Core Workflow

  1. Provider Integration: Register providers in config/packages/chamber_orchestra_translation.yaml:

    chamber_orchestra_translation:
        providers:
            google:
                enabled: true
                api_key: '%env(GOOGLE_TRANSLATE_API_KEY)%'
    

    Extend AbstractProvider to add custom providers (e.g., AzureProvider).

  2. Service Injection: Use dependency injection for translation services:

    public function __construct(
        private TranslationService $translator,
        private CacheManagerInterface $cache
    ) {}
    
  3. Caching: Enable caching in config:

    chamber_orchestra_translation:
        cache:
            enabled: true
            provider: 'app.cache.app'
    

    Cache keys follow the pattern: translation:{source}:{target}:{text}.

  4. Batch Processing: Use BatchTranslationService for bulk translations:

    $batch = $batchTranslator->translateBatch([
        ['text' => 'Hello', 'target' => 'es'],
        ['text' => 'World', 'target' => 'fr'],
    ]);
    

Integration Tips

  • Symfony Forms: Add a TranslationType for form fields:

    use ChamberOrchestra\TranslationBundle\Form\Type\TranslationType;
    
    $builder->add('translatedText', TranslationType::class, [
        'source' => 'en',
        'target' => 'es',
    ]);
    
  • Twig Integration: Extend the bundle’s Twig extension to add filters:

    {{ 'Hello'|translate('en', 'es') }}
    
  • Event Listeners: Subscribe to TranslationEvent for pre/post-processing:

    use ChamberOrchestra\TranslationBundle\Event\TranslationEvent;
    
    public function onTranslation(TranslationEvent $event) {
        $event->setText(strtoupper($event->getText())); // Example modifier
    }
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits:

    • Google/DeepL providers may throttle requests. Implement retry logic or use BatchTranslationService.
    • Monitor ProviderException for rate-limit errors.
  2. Cache Invalidation:

    • Clear cache manually after config changes:
      php bin/console cache:clear
      
    • Avoid long-lived cache keys for dynamic translations.
  3. Provider-Specific Quirks:

    • Google: Requires GOOGLE_TRANSLATE_API_KEY; supports 100+ languages.
    • DeepL: Needs DEEPL_AUTH_KEY; better for high-quality translations but pricier.
    • Test providers individually to validate API credentials.
  4. Text Length Limits:

    • Some providers (e.g., Google) cap text length at 5,000 characters. Split long texts or use batch processing.

Debugging Tips

  • Enable Logging: Add to config/packages/monolog.yaml:

    handlers:
        translation:
            type: stream
            path: '%kernel.logs_dir%/translation.log'
            level: debug
    

    Logs appear in var/log/translation.log.

  • Check Provider Responses: Inspect raw API responses for errors:

    $translator->translate('Hello', 'en', 'es', true); // Enable debug mode
    
  • Test Locally: Use TranslationService::setTestMode(true) to bypass API calls and return mock responses.

Extension Points

  1. Custom Providers: Extend AbstractProvider and register in services.yaml:

    services:
        App\Translation\Provider\MyProvider:
            tags: ['chamber_orchestra_translation.provider']
    
  2. Post-Processing: Implement PostProcessorInterface to modify translations:

    use ChamberOrchestra\TranslationBundle\Service\PostProcessorInterface;
    
    class UppercasePostProcessor implements PostProcessorInterface {
        public function process(string $text, string $source, string $target): string {
            return strtoupper($text);
        }
    }
    

    Register in config:

    chamber_orchestra_translation:
        post_processors:
            - App\Translation\UppercasePostProcessor
    
  3. Event Subscribers: Listen for TranslationEvent to intercept translations:

    use ChamberOrchestra\TranslationBundle\Event\TranslationEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class TranslationSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents(): array {
            return [
                TranslationEvent::NAME => 'onTranslation',
            ];
        }
    
        public function onTranslation(TranslationEvent $event) {
            // Modify $event->getText() or $event->setTargetLanguage()
        }
    }
    

Configuration Quirks

  • Fallback Languages: Define fallbacks in config to handle unsupported language pairs:

    chamber_orchestra_translation:
        fallback_languages:
            'zh-TW': 'zh-CN' # Taiwanese → Simplified Chinese
    
  • Environment Variables: Use %env() for sensitive keys (e.g., API keys) in config/packages/chamber_orchestra_translation.yaml:

    providers:
        google:
            api_key: '%env(GOOGLE_TRANSLATE_API_KEY)%'
    
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