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

Yandex Translator Bundle Laravel Package

chiarillomax/yandex-translator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chiarillomax/yandex-translator-bundle
    

    Register the bundle in app/AppKernel.php:

    new \Yandex\TranslatorBundle\YandexTranslatorBundle(),
    
  2. Configuration: Add Yandex API key to config.yml (or parameters.yml):

    parameters:
        yandex_translator.key: 'your_yandex_api_key_here'
    
  3. First Use Case: Translate text in a controller:

    use Yandex\TranslatorBundle\YandexTranslator;
    use Yandex\TranslatorBundle\Model\Key;
    
    $translator = $this->get('yandex.translator');
    $key = new Key();
    $key->setValue($this->container->getParameter('yandex_translator.key'));
    
    $translation = $translator->createRequest()
        ->setKey($key->getValue())
        ->setText('Hello World')
        ->setFrom('en')
        ->setTo('es')
        ->send();
    
    return $translation->getText(); // "Hola Mundo"
    

Implementation Patterns

Core Workflow

  1. Request Creation: Always use createRequest() to build translation requests:

    $request = $this->get('yandex.translator')->createRequest();
    
  2. Chaining Methods: Chain setKey(), setText(), setFrom(), and setTo() for clarity:

    $request->setKey($apiKey)
            ->setText($text)
            ->setFrom('en')
            ->setTo('fr');
    
  3. Service Integration: Inject the translator service into controllers/services:

    class TranslationService {
        protected $translator;
    
        public function __construct(YandexTranslator $translator) {
            $this->translator = $translator;
        }
    }
    
  4. Batch Translations: Loop through texts and translate in bulk (if API supports it):

    foreach ($texts as $text) {
        $translation = $this->translator->createRequest()
            ->setKey($apiKey)
            ->setText($text)
            ->setFrom('en')
            ->setTo('de')
            ->send();
    }
    
  5. Error Handling: Wrap requests in try-catch blocks:

    try {
        $translation = $request->send();
    } catch (\Exception $e) {
        $this->logger->error('Translation failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony2:

    • The bundle is designed for Symfony 2.x (last release in 2016). Ensure compatibility with your version.
    • Avoid using in Symfony 3+/4+/5+ without forking/updating.
  2. API Key Management:

    • Hardcoding keys in controllers violates DRY principles. Use parameters.yml or environment variables:
      # config/packages/dev/yandex_translator.yaml
      yandex_translator:
          key: '%env(YANDEX_TRANSLATOR_KEY)%'
      
  3. Rate Limits:

    • Yandex API may throttle requests. Implement caching (e.g., Redis) for repeated translations:
      $cache = $this->get('cache.app');
      $cacheKey = md5($text . $from . $to);
      if (!$cache->has($cacheKey)) {
          $translation = $request->send();
          $cache->set($cacheKey, $translation->getText(), 3600); // Cache for 1 hour
      } else {
          $translation = $cache->get($cacheKey);
      }
      
  4. Language Codes:

  5. Service Not Found:

    • If $this->get('yandex.translator') fails, ensure:
      • The bundle is registered in AppKernel.php.
      • Composer autoload is dumped (composer dump-autoload).

Debugging Tips

  1. Enable API Debugging: Add a debug flag to log requests/responses:

    $request->setDebug(true); // If supported by the bundle
    
  2. Check HTTP Status: Inspect the raw response for errors:

    $response = $request->send();
    if ($response->getStatusCode() !== 200) {
        throw new \RuntimeException('API Error: ' . $response->getContent());
    }
    
  3. Update Dependencies: If issues arise, check for outdated dependencies (e.g., guzzlehttp/guzzle):

    composer update guzzlehttp/guzzle
    

Extension Points

  1. Custom Response Handling: Extend the YandexTranslator service to add logic:

    class CustomYandexTranslator extends YandexTranslator {
        public function translateWithFallback($text, $from, $to) {
            try {
                return parent::createRequest()
                    ->setText($text)
                    ->setFrom($from)
                    ->setTo($to)
                    ->send()->getText();
            } catch (\Exception $e) {
                return $text; // Fallback to original text
            }
        }
    }
    
  2. Event Listeners: Dispatch events before/after translation (e.g., for logging):

    // In services.yml
    services:
        app.translation_listener:
            class: AppBundle\EventListener\TranslationListener
            tags:
                - { name: kernel.event_listener, event: yandex.translation, method: onTranslation }
    
  3. Configuration Overrides: Override default settings via config.yml:

    yandex_translator:
        default_from: 'en'
        default_to: 'es'
        timeout: 30
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony