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

Language Bundle Laravel Package

bordeux/language-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require bordeux/language-bundle
    

    Register the bundle in config/app.php under providers:

    Bordeaux\LanguageBundle\BordeauxLanguageBundle::class,
    

    And import the routing in config/app.php under routes:

    Bordeaux\LanguageBundle\Routing\LanguageRouting::class,
    
  2. Database Setup Run migrations to create the required tables (check src/Resources/migrations/ for schema):

    php artisan migrate
    

    The bundle expects tables for:

    • language (stores language codes, names, etc.)
    • translation (stores key-value pairs per language)
    • currency (if using currency features)
  3. First Use Case: Basic Translation Load translations dynamically in a controller:

    use Bordeaux\LanguageBundle\Manager\TranslationManager;
    
    class MyController extends Controller
    {
        public function show()
        {
            $translationManager = $this->container->get('bordeux.language.manager.translation');
            $translation = $translationManager->getTranslation('my_key', 'en'); // 'en' = language code
            return view('page', ['message' => $translation]);
        }
    }
    
  4. SonataAdmin Integration Enable the bundle’s SonataAdmin provider in config/packages/sonata_admin.php:

    providers:
        - Bordeaux\LanguageBundle\Sonata\LanguageAdmin
    

    Clear cache:

    php artisan cache:clear
    

Implementation Patterns

Translation Management Workflow

  1. Storing Translations Use the TranslationManager to save translations dynamically:

    $translationManager = $this->container->get('bordeux.language.manager.translation');
    $translationManager->saveTranslation('my_key', 'Hello, {name}!', 'en');
    
  2. Fetching Translations Retrieve translations with fallback to default language:

    $translation = $translationManager->getTranslation('my_key', 'fr', 'en'); // Fallback to 'en' if 'fr' missing
    
  3. Dynamic Placeholders Replace placeholders in translations:

    $message = $translationManager->getTranslation('greeting', 'en');
    $rendered = str_replace('{name}', 'John', $message); // Manual replacement (no built-in interpolation)
    
  4. Language Switching Override the current language in a request:

    $request->setLocale('es'); // Manually set language
    

Currency Integration (If Used)

  1. Storing Currency Values Save currency rates dynamically:

    $currencyManager = $this->container->get('bordeux.language.manager.currency');
    $currencyManager->saveRate('USD', 'EUR', 0.85);
    
  2. Fetching Converted Values Convert amounts between currencies:

    $convertedAmount = $currencyManager->convert(100, 'USD', 'EUR'); // Returns 85.00
    

SonataAdmin Integration

  1. Admin Panel Configuration Extend the LanguageAdmin class to customize fields:

    use Bordeaux\LanguageBundle\Sonata\LanguageAdmin as BaseLanguageAdmin;
    
    class CustomLanguageAdmin extends BaseLanguageAdmin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            $formMapper->add('name', 'text', ['label' => 'Language Name']);
            // Custom fields here
        }
    }
    
  2. Translation CRUD Use the SonataAdmin panel to:

    • Add/edit languages.
    • Manage translation keys/values per language.
    • (If currency is enabled) manage rates.
  3. Routing Access the admin panel at /admin/language (configurable in routing.yml).


Integration with Laravel’s Translation System

  1. Fallback to Laravel’s lang Files Combine with Laravel’s built-in translations for hybrid workflows:

    $translation = $translationManager->getTranslation('key') ?: __('fallback.key');
    
  2. Publish Translations Publish the bundle’s translations (if any) to extend them:

    php artisan vendor:publish --provider="Bordeux\LanguageBundle\BordeauxLanguageBundle" --tag=translations
    

Gotchas and Tips

Pitfalls

  1. Deprecated/Archived Package

    • Last release in 2016; may not work with modern Laravel (5.5+) or PHP 7.4+.
    • Mitigation: Fork the repo and update dependencies manually (e.g., Symfony components, Doctrine).
  2. No Built-in Interpolation

    • Placeholders (e.g., {name}) require manual str_replace or regex. Consider extending the TranslationManager:
      $translationManager->setInterpolator(function ($translation, $params) {
          return strtr($translation, $params);
      });
      
  3. SonataAdmin Version Mismatch

    • Bundle assumes SonataAdmin 2.x. For SonataAdmin 3.x, override templates or update the bundle’s SonataAdmin integration.
  4. Database Schema Assumptions

    • Tables (language, translation, currency) must exist. If migrations fail, manually create them or adjust the bundle’s schema.
  5. No Cache Busting

    • Translations aren’t cached by default. For performance, implement a cache layer:
      Cache::remember("translation_{$key}_{$locale}", 3600, function() use ($key, $locale) {
          return $translationManager->getTranslation($key, $locale);
      });
      

Debugging Tips

  1. Check Database Records Verify translations/currencies exist in the DB:

    SELECT * FROM translation WHERE key = 'my_key';
    
  2. Enable Debugging Add logging to the TranslationManager:

    $translationManager->setLogger($this->container->get('logger'));
    
  3. Override Services Replace the TranslationManager with a debug version:

    # config/services.yaml
    Bordeaux\LanguageBundle\Manager\TranslationManager:
        arguments:
            - '@database_connection'
            - '@logger' # Inject logger for debugging
    

Extension Points

  1. Custom Translation Sources Extend TranslationManager to support additional sources (e.g., API, files):

    class ApiTranslationManager extends TranslationManager
    {
        public function getTranslation($key, $locale = null)
        {
            $apiTranslation = $this->fetchFromApi($key, $locale);
            return $apiTranslation ?: parent::getTranslation($key, $locale);
        }
    }
    
  2. Event Listeners Listen for translation events (if the bundle emits them):

    use Bordeaux\LanguageBundle\Event\TranslationEvent;
    
    Event::listen(TranslationEvent::class, function (TranslationEvent $event) {
        // Log or modify translations before saving
    });
    
  3. Custom Validation Add validation to translations (e.g., length, format):

    $translationManager->setValidator(function ($translation) {
        return strlen($translation) < 200; // Example: enforce max length
    });
    

Performance Quirks

  1. N+1 Query Problem Fetching translations in loops triggers multiple queries. Use eager loading:

    $translations = $translationManager->getTranslations(['key1', 'key2'], 'en');
    
  2. Locale Detection The bundle may not auto-detect locale. Override the LocaleListener:

    $request->setLocale($this->detectLocale()); // Custom logic
    

Migration Tips

  1. Backward Compatibility If upgrading from an older version, check for:

    • Changed method signatures (e.g., getTranslation() parameters).
    • Deprecated services (e.g., bordeux.language.manager vs. bordeux.language.manager.translation).
  2. Data Migration Export/import translations if schema changes:

    php artisan db:seed --class=LanguageSeeder
    
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