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

Locale Bundle Laravel Package

sylius/locale-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sylius/locale-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Sylius\Bundle\LocaleBundle\SyliusLocaleBundle::class => ['all' => true],
    ];
    
  2. Configuration: Override default locales in config/packages/sylius_locale.yaml:

    sylius_locale:
        locales: ['en_US', 'fr_FR', 'es_ES']  # Customize as needed
        default_locale: 'en_US'
    
  3. First Use Case:

    • Route-based locale switching: Enable the locale router requirement in config/routes.yaml:

      sylius_locale:
          resource: "@SyliusLocaleBundle/Resources/config/routing.yaml"
      

      Access routes like /en_US/products or /fr_FR/products.

    • Twig integration: Use {{ app.request.locale }} in templates to dynamically render locale-specific content.


Implementation Patterns

Core Workflows

  1. Locale-Aware Routing:

    • Leverage the locale router requirement to enforce locale prefixes (e.g., /{_locale}/...).
    • Use sylius_locale.locale event listeners to modify behavior per locale (e.g., redirect to default locale if unsupported).
  2. Dynamic Locale Switching:

    • Implement a locale switcher in your UI (e.g., dropdown) using the sylius_locale.switch_locale route:
      <a href="{{ path('sylius_locale_switch', {'_locale': 'fr_FR'}) }}">Français</a>
      
    • Store the preferred locale in a cookie or session for persistence.
  3. Translation Integration:

    • Pair with symfony/translation for locale-specific messages:
      # config/packages/translation.yaml
      framework:
          translator:
              paths: ['%kernel.project_dir%/translations']
              default_path: '%kernel.project_dir%/translations'
      
    • Use {{ 'message.key'|trans }} in Twig with automatic locale fallback.
  4. Database-Driven Locales:

    • Extend the bundle to fetch locales from a database table (e.g., Locale entity) by overriding the LocaleProvider service.
  5. API Locale Handling:

    • For APIs, use the Accept-Language header to set the locale:
      // src/EventListener/LocaleListener.php
      use Sylius\Component\Locale\Context\LocaleContextInterface;
      
      public function onKernelRequest(GetResponseEvent $event): void
      {
          $request = $event->getRequest();
          $locale = $request->headers->get('Accept-Language', $this->localeContext->getLocale());
          $this->localeContext->setLocale($locale);
      }
      

Gotchas and Tips

Common Pitfalls

  1. Locale Prefix Conflicts:

    • Ensure your routes do not conflict with the {_locale} requirement. Use requirements: _locale: \w+ in route definitions to enforce valid locale patterns.
  2. Caching Issues:

    • Clear the cache after changing sylius_locale.locales:
      php bin/console cache:clear
      
    • For production, use cache:pool:clear sylius_locale to avoid full cache rebuilds.
  3. Fallback Locale Misconfiguration:

    • If a locale is unsupported, the bundle defaults to en_US. Override this in the LocaleProvider or configure a custom fallback:
      sylius_locale:
          fallback_locale: 'en_US'
      
  4. Twig Auto-Reloading:

    • If translations aren’t updating in Twig, check that debug: true is set in framework config and restart the dev server.

Debugging Tips

  • Check Current Locale:
    // In a controller or Twig
    dump($this->get('sylius.locale.context')->getLocale());
    
  • Validate Locale Format: The bundle expects BCP 47 locales (e.g., en_US, not en). Use Locale::getPrimaryLanguage() to validate.

Extension Points

  1. Custom Locale Provider: Override the default provider to fetch locales dynamically:

    # config/services.yaml
    Sylius\Component\Locale\Provider\LocaleProviderInterface sylius.locale.provider:
        class: App\Locale\CustomLocaleProvider
        arguments:
            - '@your_database_service'
    
  2. Event Listeners: Subscribe to sylius.locale.switch to log locale changes or trigger side effects:

    use Sylius\Component\Locale\Event\LocaleSwitchEvent;
    
    public function onLocaleSwitch(LocaleSwitchEvent $event): void
    {
        // Example: Update user's preferred locale in DB
        $event->getUser()->setPreferredLocale($event->getLocale());
    }
    
  3. Route Overrides: Extend or replace the default routing by copying SyliusLocaleBundle/Resources/config/routing.yaml to config/routes/sylius_locale.yaml and modifying it.

Performance

  • Preload Locales: If locales are static, define them in sylius_locale.locales to avoid runtime lookups.
  • Avoid Runtime Locale Lookups: Cache the list of supported locales in a service if fetched dynamically (e.g., from a database).
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.
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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