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

Oro Deepl Laravel Package

diglin/oro-deepl

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require vendor/deepl-translation-package

Publish the configuration file (if needed) and set your DeepL API key in .env:

DEEPL_API_KEY=your_api_key_here

Start using DeepL translations directly in your Laravel app:

use DeepL\Translation;

// Basic translation
$translation = Translation::translate('Hello world', 'en', 'es');

Implementation Patterns

Workflow Integration

  1. Service Layer Abstraction Wrap DeepL calls in a service class (e.g., TranslationService) to centralize logic and handle retries/fallbacks:

    class TranslationService {
        public function translate(string $text, string $sourceLang, string $targetLang): string {
            return Translation::translate($text, $sourceLang, $targetLang);
        }
    }
    
  2. Queueable Jobs Offload translations to a queue (e.g., TranslateTextJob) for async processing:

    class TranslateTextJob implements ShouldQueue {
        public function handle() {
            $this->translateText();
        }
    }
    
  3. Model Observers Auto-translate fields on model events (e.g., created):

    class PostObserver {
        public function created(Post $post) {
            $post->translated_content = Translation::translate(
                $post->content,
                'en',
                $post->locale
            );
            $post->save();
        }
    }
    

SDK-Specific Patterns

  • Batch Processing Leverage the official SDK’s batch endpoints for bulk translations:

    Translation::translateBatch([
        ['text' => 'Hello', 'target_lang' => 'es'],
        ['text' => 'World', 'target_lang' => 'fr']
    ]);
    
  • Glossary Support Use DeepL’s glossary feature via the SDK’s setGlossary method:

    Translation::setGlossary('your_glossary_id');
    

Gotchas and Tips

Breaking Changes (1.2.0)

  • SDK Migration: The package now uses the official DeepL PHP SDK, which may introduce:
    • Method Signature Changes: Check the SDK docs for updated parameters (e.g., target_lang vs. targetLanguage).
    • Deprecated Aliases: Old method names (e.g., translateText()) may no longer work. Use the SDK’s standard methods (e.g., translateText()translate()).
    • Error Handling: The SDK throws exceptions (e.g., DeepL\Exception\DeepLApiException). Wrap calls in try-catch blocks:
      try {
          $result = Translation::translate('text', 'en', 'es');
      } catch (\DeepL\Exception\DeepLApiException $e) {
          Log::error($e->getMessage());
          return back()->withErrors(['translation' => 'Failed to translate']);
      }
      

Performance Tips

  • Rate Limiting: The SDK respects DeepL’s rate limits. Implement exponential backoff for retries:

    use DeepL\Exception\RateLimitExceededException;
    
    try {
        $result = Translation::translate($text, $source, $target);
    } catch (RateLimitExceededException $e) {
        sleep(2); // Wait 2 seconds before retrying
        retry();
    }
    
  • Caching: Cache translations for repeated requests (e.g., same text + lang pair):

    $cacheKey = "deepl:{$source}_{$target}_{md5($text)}";
    if (cache()->has($cacheKey)) {
        return cache()->get($cacheKey);
    }
    $translation = Translation::translate($text, $source, $target);
    cache()->put($cacheKey, $translation, now()->addHours(1));
    return $translation;
    

Debugging

  • Enable SDK Logging: Configure the SDK to log requests/responses:
    Translation::setLogger(function ($message) {
        Log::debug('DeepL SDK: ' . $message);
    });
    
  • Validate API Key: Ensure your .env key is correct and has sufficient credits. Test with a small request first:
    if (!Translation::authenticate()) {
        throw new \RuntimeException('Invalid DeepL API key');
    }
    

Extension Points

  • Custom SDK Configuration: Extend the SDK’s DeepL\DeepL class to add middleware or interceptors:
    $deepl = new \DeepL\DeepL($apiKey);
    $deepl->setMiddleware(function ($request) {
        // Add custom headers or modify requests
    });
    
  • Fallback Strategies: Implement fallback logic for failed translations (e.g., use Google Translate):
    public function translateWithFallback(string $text, string $source, string $target): string {
        try {
            return Translation::translate($text, $source, $target);
        } catch (\Exception $e) {
            return app(\App\Services\GoogleTranslateService::class)->translate($text, $source, $target);
        }
    }
    
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