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

Custom I18N Router Bundle Laravel Package

eb78/custom-i18n-router-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require eb78/custom-i18n-router-bundle
    

    Register the bundle in config/bundles.php:

    EB78\CustomI18nRouterBundle\EB78CustomI18nRouterBundle::class => ['all' => true],
    
  2. Configure Locales Add available_locales and default_locale to config/packages/eb78_custom_i18n_router.yaml:

    parameters:
        available_locales: ['en-us', 'fr-fr']
        default_locale: 'en-us'
    
  3. Define Route Mappings Create a YAML file (e.g., config/i18n_en-us.yaml) with locale-specific routes:

    parameters:
        i18n_en-us:
            prefix: ""          # Optional URL prefix (e.g., "/en")
            name: "english"     # Display name
            localeUId: 1        # Unique ID for the locale
            locale: "en_US"     # Symfony locale code
            host: "example.com" # Domain for this locale
            routes:
                home: /home/
                contact: /contact/
    
  4. First Use Case Generate a locale-aware URL in a controller:

    use EB78\CustomI18nRouterBundle\Router\I18nRouter;
    
    public function index(I18nRouter $router)
    {
        return $router->generate('home', ['_locale' => 'fr-fr']);
    }
    

Implementation Patterns

Core Workflows

  1. Dynamic Route Generation Use the I18nRouter service to generate locale-specific URLs:

    $url = $router->generate('contact', ['_locale' => 'fr-fr']);
    // Outputs: "https://yourdomain.fr/contactez-nous/"
    
  2. Locale Switching Redirect users to a different locale while preserving the current route:

    $router->redirectToLocale('en-us', $request->get('_route'));
    
  3. Host-Based Routing Configure host in the locale YAML to enforce domain-level routing:

    host: "fr.example.com"
    

    The router will automatically redirect to the correct host.

  4. Prefix-Based Routing Use the prefix parameter to add a path segment (e.g., /fr/):

    prefix: "/fr"
    routes:
        home: "/accueil/"
    

    Generated URL: /fr/accueil/.

  5. Integration with Symfony’s Router Extend the default router to include locale logic:

    // In services.yaml
    services:
        App\Router\CustomRouter:
            decorates: router.default
            arguments: ['@.inner']
    

Best Practices

  • Consistent Naming: Use snake_case for route names (e.g., user_profile).
  • Fallback Logic: Define a fallback locale in default_locale for missing translations.
  • Testing: Test locale transitions and host redirects in isolation.
  • Caching: Cache generated routes if performance is critical (Symfony’s router cache works here).

Gotchas and Tips

Pitfalls

  1. Locale File Naming

    • Files must follow the pattern i18n_{locale}.yaml (e.g., i18n_fr-fr.yaml).
    • Misspelled filenames will silently fail; validate with:
      find config -name "i18n_*.yaml"
      
  2. Host vs. Prefix Conflicts

    • Avoid mixing host and prefix for the same locale. Example:
      # Bad: Both host and prefix will override each other.
      host: "fr.example.com"
      prefix: "/fr"
      
    • Use either host-based routing (for subdomains) or prefix-based (for paths).
  3. Route Parameter Mismatches

    • Ensure route names in YAML match those in your controllers/annotations. Example:
      routes:
          user_show: "/users/{id}"  # Must match `@Route("/users/{id}", name="user_show")`
      
  4. Locale Parameter Overrides

    • The _locale parameter in generate() takes precedence over the default locale. Example:
      $router->generate('home', ['_locale' => 'fr-fr']); // Forces French, even if default is 'en-us'.
      
  5. Symfony 4+ Compatibility

    • The bundle targets Symfony 2.8. For Symfony 4/5, wrap the bundle in a custom bundle or use a compatibility layer:
      // In a Symfony 5 project, create a bridge bundle:
      use Symfony\Component\HttpKernel\Bundle\Bundle;
      
      class CustomI18nRouterBridgeBundle extends Bundle {}
      

Debugging Tips

  1. Check Generated URLs Dump the router’s internal mappings:

    $router->getRouteCollection()->getResources();
    
  2. Validate Locale Config Use the EB78\CustomI18nRouterBundle\Manager\LocaleManager service to list available locales:

    $locales = $this->get('eb78_custom_i18n_router.locale_manager')->getAvailableLocales();
    
  3. Enable Debug Mode Add this to config/packages/dev/eb78_custom_i18n_router.yaml:

    parameters:
        debug: true
    

    This logs route generation and locale resolution.

  4. Handle Missing Routes Catch EB78\CustomI18nRouterBundle\Exception\LocaleRouteNotFoundException:

    try {
        $url = $router->generate('nonexistent_route');
    } catch (LocaleRouteNotFoundException $e) {
        return new Response('Route not found', 404);
    }
    

Extension Points

  1. Custom Route Loaders Extend EB78\CustomI18nRouterBundle\Loader\YamlFileLoader to support additional formats (e.g., JSON):

    class JsonFileLoader extends YamlFileLoader {
        public function load($resource, $type = null) { /* ... */ }
    }
    
  2. Dynamic Locale Resolution Override EB78\CustomI18nRouterBundle\Resolver\LocaleResolver to add logic (e.g., user preferences):

    class CustomLocaleResolver extends LocaleResolver {
        public function getLocale(Request $request) {
            $userLocale = $request->getSession()->get('user_locale');
            return $userLocale ?: parent::getLocale($request);
        }
    }
    
  3. Add Locale-Specific Middleware Use Symfony’s middleware pipeline to modify requests/responses:

    // In config/packages/dev/http_client.yaml
    http_client:
        middleware:
            - EB78\CustomI18nRouterBundle\Middleware\LocaleMiddleware
    
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