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

arthem/locale-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arthem/locale-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Arthem\LocaleBundle\ArthemLocaleBundle::class => ['all' => true],
    ];
    
  2. Configure Locales: Define supported locales in config/packages/arthem_locale.yaml:

    arthem_locale:
        locales:
            - en
            - fr
            - fr_CA
    
  3. First Use Case:

    • Switching Locales Dynamically: Inject the LocaleListener into a controller/service:
      use Arthem\LocaleBundle\EventListener\LocaleListener;
      
      public function __construct(private LocaleListener $localeListener) {}
      
      public function switchLocale(string $locale): void
      {
          $this->localeListener->setLocale($locale);
      }
      
      Call it from a route:
      Route::get('/set-locale/{locale}', [YourController::class, 'switchLocale']);
      

Implementation Patterns

Core Workflows

  1. Locale Switching in Controllers: Use dependency injection to leverage the LocaleListener:

    public function index(LocaleListener $localeListener, Request $request)
    {
        $locale = $request->get('locale', config('app.locale'));
        $localeListener->setLocale($locale);
        // ...
    }
    
  2. Middleware for Locale Persistence: Create middleware to persist locale across requests (e.g., via session):

    use Arthem\LocaleBundle\EventListener\LocaleListener;
    
    class LocaleMiddleware
    {
        public function __invoke(Request $request, LocaleListener $localeListener)
        {
            $locale = session('locale', config('app.locale'));
            $localeListener->setLocale($locale);
            return $next($request);
        }
    }
    

    Register in kernel.php:

    protected function configureMiddleware(Middleware $middleware)
    {
        $middleware->alias('locale', LocaleMiddleware::class);
        // ...
    }
    
  3. Twig Integration: Access the current locale in Twig:

    {{ app.request.attributes.get('_locale') }}
    

    Or use the bundle’s provided filters:

    {{ 'Hello'|trans({locale: app.request.attributes.get('_locale')}) }}
    
  4. Route-Based Locale Switching: Use Symfony’s LocaleListener (if extended) or custom logic to parse locales from routes:

    # config/routes.yaml
    _locale:
        path: /{_locale}
        defaults:
            _locale: en
            _controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
            route: home
        requirements:
            _locale: en|fr|fr_CA
    

Integration Tips

  • Translation Integration: Pair with Symfony’s Translation component for seamless translations:
    $translator = $this->get('translator');
    $translator->trans('key', [], null, $locale);
    
  • Database Locale Storage: Store user-preferred locales in the database and hydrate the LocaleListener on auth:
    $user->locale; // e.g., 'fr_CA'
    $localeListener->setLocale($user->locale);
    
  • Fallback Logic: Configure fallback locales in arthem_locale.yaml:
    arthem_locale:
        locales:
            - en
            - fr
        fallback_locale: en
    

Gotchas and Tips

Pitfalls

  1. Locale Validation: The bundle does not validate locales against the configured list by default. Always sanitize input:

    $validLocales = config('arthem_locale.locales');
    if (!in_array($locale, $validLocales)) {
        throw new \InvalidArgumentException("Invalid locale: {$locale}");
    }
    
  2. Intl Extension Dependency: The package requires ext-intl for full locale features (e.g., locale-aware sorting). Test locally:

    php -m | grep intl
    

    If missing, install via:

    pecl install intl
    
  3. Session vs. Request Locale: Without middleware, the locale resets per-request. Use session storage for persistence:

    session(['locale' => $locale]);
    
  4. Twig Cache Invalidation: Changing locales dynamically may require Twig cache clearing:

    php bin/console cache:clear
    

    Or configure runtime compilation in config/packages/twig.yaml:

    twig:
        runtime_loader: Symfony\Component\Twig\Loader\FilesystemLoader
    

Debugging

  • Check Current Locale: Dump the locale in a controller:
    dump(app()->getLocale()); // Symfony's locale
    dump($localeListener->getLocale()); // Bundle's locale
    
  • Log Locale Switches: Extend LocaleListener to log changes:
    use Psr\Log\LoggerInterface;
    
    class CustomLocaleListener extends LocaleListener
    {
        public function __construct(private LoggerInterface $logger) {}
    
        public function setLocale(string $locale): void
        {
            $this->logger->info("Locale switched to: {$locale}");
            parent::setLocale($locale);
        }
    }
    

Extension Points

  1. Custom Locale Provider: Implement Arthem\LocaleBundle\Provider\LocaleProviderInterface for dynamic locales:

    class UserLocaleProvider implements LocaleProviderInterface
    {
        public function getLocale(): string
        {
            return auth()->user()->locale ?? config('app.locale');
        }
    }
    

    Register in services:

    # config/services.yaml
    services:
        Arthem\LocaleBundle\Provider\LocaleProviderInterface: '@user_locale_provider'
    
  2. Event Listeners: Subscribe to LocaleChangedEvent (if exposed) for side effects:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Arthem\LocaleBundle\Event\LocaleChangedEvent;
    
    class LocaleSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                LocaleChangedEvent::class => 'onLocaleChanged',
            ];
        }
    
        public function onLocaleChanged(LocaleChangedEvent $event): void
        {
            // Redirect to locale-specific URL, etc.
        }
    }
    
  3. Override Default Behavior: Extend the bundle’s services in config/packages/arthem_locale.yaml:

    services:
        Arthem\LocaleBundle\EventListener\LocaleListener:
            arguments:
                $fallbackLocale: 'en_US'
                $supportedLocales: ['%kernel.project_dir%/config/locales.php']
    

Configuration Quirks

  • Locale Format: The bundle expects ICU locale strings (e.g., fr_CA). Avoid shorthand (e.g., fr) unless explicitly configured.
  • Priority: The bundle’s locale listener runs after Symfony’s default listener. Override priority in config/packages/arthem_locale.yaml:
     services:
         Arthem\LocaleBundle\EventListener\LocaleListener:
             tags:
                 - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 255 }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware