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

I18N Routing Bundle Laravel Package

besimple/i18n-routing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require besimple/i18n-routing-bundle
    

    Register the bundle in AppKernel.php:

    new BeSimple\I18nRoutingBundle\BeSimpleI18nRoutingBundle(),
    
  2. Configure: Add to config.yml:

    be_simple_i18n_routing: ~
    
  3. Define Routes: Create a dedicated routing file (e.g., src/MyBundle/Resources/config/routing/i18n.yml) and import it with the be_simple_i18n type:

    my_i18n_routes:
        resource: "@MyBundle/Resources/config/routing/i18n.yml"
        type: be_simple_i18n
        prefix:
            en: /website
            fr: /site
            de: /webseite
    
  4. Define I18n Routes: In i18n.yml, use the i18n prefix for routes:

    home:
        path: /{_locale}/home
        defaults: { _controller: MyBundle:Default:index }
        requirements:
            _locale: en|fr|de
    
  5. First Use Case: Access /en/home or /fr/accueil (if translated). The locale (_locale) is automatically detected and updated in the URL.


Implementation Patterns

Routing Workflows

  1. Locale-Aware Routing:

    • Use {_locale} as a route parameter to enforce locale detection.
    • Example:
      product:
          path: /{_locale}/product/{id}
          defaults: { _controller: MyBundle:Product:show }
      
    • Access via /en/product/123 or /fr/produit/123.
  2. Prefixes for Language Segments:

    • Define language-specific prefixes in the prefix key during route import:
      my_routes:
          resource: "@MyBundle/Resources/config/routing/i18n.yml"
          type: be_simple_i18n
          prefix:
              en: /en
              fr: /fr
      
    • Routes like /en/home or /fr/accueil are generated automatically.
  3. Dynamic Locale Switching:

    • Use the be_simple_i18n_routing.switch_locale route to switch locales dynamically:
      _switch_locale:
          path: /{_locale}
          defaults: { _controller: BeSimpleI18nRoutingBundle:Routing:switchLocale }
      
    • Link to /fr to switch from /en/home to /fr/accueil.
  4. Parameter Translation:

    • Translate route parameters (e.g., id) between locales using a translator or Doctrine DBAL backend.
    • Configure in config.yml:
      be_simple_i18n_routing:
          translator: ~ # Uses Symfony Translator
          # OR
          dbal:
              driver: pdo_mysql
              host: localhost
              dbname: my_db
              user: root
              password: secret
      
  5. Integration with Controllers:

    • Access the current locale in controllers via the Request object:
      $locale = $request->get('_locale');
      
    • Redirect to translated URLs using the UrlGenerator:
      $url = $this->generateUrl('home', ['_locale' => 'fr']);
      
  6. Fallback Locales:

    • Define fallback locales for missing translations:
      be_simple_i18n_routing:
          fallback_locale: en
      

Gotchas and Tips

Common Pitfalls

  1. Locale Parameter Conflicts:

    • Ensure {_locale} does not conflict with other route parameters. Use _locale (with underscore) to avoid naming collisions.
    • Example of conflict:
      # Bad: 'locale' conflicts with other parameters
      path: /{locale}/home
      
    • Fix:
      path: /{_locale}/home
      
  2. Caching Issues:

    • Clear the route cache after adding/updating I18n routes:
      php bin/console cache:clear
      
    • For production, use:
      php bin/console cache:pool:clear cache.app
      
  3. Missing Locale Requirements:

    • Always define _locale requirements to avoid 404 errors:
      requirements:
          _locale: en|fr|de
      
    • Without this, routes like /xyz/home may fail silently.
  4. Prefix Overrides:

    • Prefixes in the type: be_simple_i18n block override individual route paths. Ensure consistency:
      # Prefix /en/ overrides the path in the route
      my_routes:
          prefix:
              en: /custom-en
      
      # Route path becomes /custom-en/home, not /en/home
      home:
          path: /{_locale}/home
      
  5. Parameter Translation Quirks:

    • If using Doctrine DBAL for parameter translation, ensure the table structure matches expectations:
      CREATE TABLE route_parameters (
          locale VARCHAR(10),
          parameter VARCHAR(50),
          value VARCHAR(255),
          PRIMARY KEY (locale, parameter)
      );
      
    • Cache invalidation is manual; clear the cache after updates:
      php bin/console cache:clear
      
  6. Symfony 4+ Compatibility:

    • The bundle is designed for Symfony 2/3. For Symfony 4+, use the auto-import feature in config/packages/routing.yml:
      imports:
          - resource: ../src/MyBundle/Resources/config/routing/i18n.yml
            type: be_simple_i18n
      

Debugging Tips

  1. Route Dumping: Use the debug:router command to inspect generated routes:

    php bin/console debug:router | grep i18n
    
  2. Locale Switching Debug:

    • Check if the _switch_locale route is registered:
      php bin/console debug:router | grep switch_locale
      
    • Ensure the controller BeSimpleI18nRoutingBundle:Routing:switchLocale is accessible.
  3. Parameter Translation Debug:

    • Verify translator backend configuration in config.yml.
    • For DBAL, check connection parameters and table data:
      php bin/console doctrine:query:sql "SELECT * FROM route_parameters"
      
  4. URL Generation Issues:

    • Use the UrlGeneratorInterface to debug URL generation:
      $generator = $this->container->get('router');
      $url = $generator->generate('home', ['_locale' => 'fr']);
      
    • Check for missing or incorrect route names.

Extension Points

  1. Custom Locale Provider: Override the default locale detection by implementing BeSimple\I18nRoutingBundle\Locale\LocaleProviderInterface:

    class CustomLocaleProvider implements LocaleProviderInterface {
        public function getLocale(Request $request) {
            return $request->headers->get('X-Locale', 'en');
        }
    }
    

    Register as a service:

    services:
        besimple_i18n_routing.locale_provider:
            class: AppBundle\Locale\CustomLocaleProvider
            tags:
                - { name: besimple_i18n_routing.locale_provider }
    
  2. Dynamic Prefixes: Use a service to generate dynamic prefixes based on runtime logic:

    class DynamicPrefixGenerator {
        public function getPrefix($locale) {
            return '/dynamic-'.$locale;
        }
    }
    

    Configure in config.yml:

    be_simple_i18n_routing:
        prefix_generator: service_id
    
  3. Event Listeners: Listen to be_simple_i18n_routing.locale_changed events to react to locale switches:

    class LocaleChangeListener {
        public function onLocaleChanged(LocaleChangedEvent $event) {
            // Custom logic (e.g., update session, redirect)
        }
    }
    

    Register as a service:

    services:
        app.locale_change_listener:
            class: AppBundle\EventListener\LocaleChangeListener
            tags:
                - { name: kernel.event_listener, event: be_simple_i18n_routing.locale_changed }
    
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