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

Smart Routing Bundle Laravel Package

dinecat/smart-routing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require dinecat/smart-routing-bundle
    

    Register it in config/bundles.php:

    return [
        // ...
        Dinecat\SmartRoutingBundle\DinecatSmartRoutingBundle::class => ['all' => true],
    ];
    
  2. First Use Case Inject the SmartRouter service into a controller or service:

    use Dinecat\SmartRoutingBundle\Router\SmartRouter;
    
    class MyController extends AbstractController
    {
        public function __construct(private SmartRouter $smartRouter) {}
    
        public function index(): Response
        {
            // Example: Generate a route with dynamic parameters
            $url = $this->smartRouter->generate('app_homepage', ['page' => 1]);
            return $this->redirect($url);
        }
    }
    
  3. Where to Look First

    • Check src/Resources/config/services.xml for core service definitions.
    • Review src/Router/SmartRouter.php for API methods (e.g., generate(), match()).
    • Inspect src/DependencyInjection/ for configuration options.

Implementation Patterns

Core Workflows

  1. Route Generation with Smart Features

    // Dynamic parameter handling
    $url = $smartRouter->generate('user_profile', ['id' => $userId, 'tab' => 'settings']);
    
    // Route with optional parameters
    $url = $smartRouter->generate('blog_post', ['slug' => 'hello-world', 'format' => 'json']);
    
  2. Reverse Routing with Constraints Use the bundle’s extended match() to parse URLs with custom logic:

    $routeParams = $smartRouter->match($request->getPathInfo());
    // Returns array with resolved parameters + custom metadata (if configured).
    
  3. Integration with Symfony’s Router Extend Symfony’s RouterInterface via dependency injection:

    # config/services.yaml
    services:
        App\Service\CustomRouter:
            arguments:
                - '@dinecat_smart_routing.router.smart_router'
    
  4. Custom Route Loaders Implement Dinecat\SmartRoutingBundle\Loader\RouteLoaderInterface to add logic (e.g., API versioning):

    class ApiVersionRouteLoader implements RouteLoaderInterface
    {
        public function load(string $resource): RouteCollection
        {
            $collection = new RouteCollection();
            // Custom logic to load routes with version prefixes.
            return $collection;
        }
    }
    
  5. Middleware for Route Enhancement Use the bundle’s events to modify routes globally:

    // src/EventListener/SmartRoutingSubscriber.php
    class SmartRoutingSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                SmartRouterEvents::ROUTE_COLLECTION_BUILD => 'onRouteCollectionBuild',
            ];
        }
    
        public function onRouteCollectionBuild(RouteCollectionBuildEvent $event)
        {
            $collection = $event->getCollection();
            // Add/modify routes dynamically.
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Undocumented API

    • The bundle lacks formal docs, so inspect SmartRouter methods via IDE autocompletion or reflection.
    • Example: generate() may support undocumented options like ['strict' => true].
  2. Configuration Overrides

    • Default configs may conflict with Symfony’s framework.router. Check config/packages/dinecat_smart_routing.yaml (if created) for overrides.
    • Example:
      dinecat_smart_routing:
          strict_requirements: true  # May break existing routes.
      
  3. Route Caching Quirks

    • The bundle may not invalidate route cache automatically. Clear cache after adding custom loaders:
      php bin/console cache:clear
      
  4. Event System Limitations

    • Events like ROUTE_COLLECTION_BUILD fire before Symfony’s router compiles routes. Use sparingly to avoid performance hits.
  5. Symfony Version Compatibility

    • The bundle claims Symfony 2 support but may have unported features for Symfony 5/6. Test thoroughly.

Debugging Tips

  1. Dump Route Collection Add this to a controller to inspect loaded routes:

    $routes = $smartRouter->getRouteCollection()->all();
    dump(array_keys($routes)); // List all route names.
    
  2. Enable Router Debugging Use Symfony’s built-in router debug:

    php bin/console debug:router
    

    Filter by dinecat_smart_routing to see bundle-specific routes.

  3. Log Route Matching Override match() to log unresolved routes:

    $smartRouter->match($path, function ($route, $parameters) {
        if (!$route) {
            $this->logger->warning("Unmatched route: {$path}");
        }
        return $parameters;
    });
    
  4. Check for Deprecated Methods Wrap calls in try-catch for undocumented behavior:

    try {
        $url = $smartRouter->generate('nonexistent_route');
    } catch (RouteNotFoundException $e) {
        // Handle gracefully.
    }
    

Extension Points

  1. Custom Route Attributes Extend Route objects by implementing a RouteAttribute class and binding it to the bundle’s route_attribute service.

  2. Dynamic Route Prefixes Use the ROUTE_COLLECTION_BUILD event to add prefixes dynamically:

    $collection->addCollection(
        new RouteCollection(),
        '/api/v' . $this->getApiVersion()
    );
    
  3. Route Parameter Transformers Override parameter handling by implementing Dinecat\SmartRoutingBundle\Resolver\ParameterResolverInterface.

  4. Integration with API Platform Use the bundle’s match() to extract API resource names from URLs:

    $routeParams = $smartRouter->match($request->getPathInfo());
    $resourceClass = $routeParams['_resource'] ?? null;
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor