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

Routing Bundle Laravel Package

raindrop/routing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

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

    "require": {
        "raindrop/routing-bundle": "dev-master"
    }
    

    Run composer update.

  2. Enable the Bundle: Add to AppKernel.php:

    new Raindrop\RoutingBundle\RaindropRoutingBundle(),
    
  3. Configure Doctrine DBAL: Add to config.yml:

    doctrine:
        dbal:
            types:
                json: Sonata\Doctrine\Types\JsonType
    
  4. Configure Routing Bundle: Add to config.yml:

    raindrop_routing:
        chain:
            routers_by_id:
                router.default: 100
                raindrop_routing.dynamic_router: 10
            replace_symfony_router: true
    
  5. Create a Route Entity: Use the Route entity to define dynamic routes:

    $route = new Route();
    $route->setName('dynamic_route');
    $route->setPath('/dynamic/path');
    $route->setController('AppBundle:Default:index');
    $em->persist($route);
    $em->flush();
    
  6. Use in Twig: Generate URLs dynamically:

    {{ url('dynamic_route') }}
    

First Use Case

Dynamic CMS Page Routes: Store page routes in the database and link them to content entities. For example:

$pageRoute = new Route();
$pageRoute->setName('page_route');
$pageRoute->setPath('/blog/{slug}');
$pageRoute->setController('AppBundle:Page:show');
$pageRoute->setRouteContent('AppBundle\Entity\Page:slug:my-post');
$em->persist($pageRoute);

This maps /blog/my-post to a Page entity with slug = 'my-post', automatically passing the entity to the show controller action.


Implementation Patterns

Usage Patterns

  1. Dynamic Route Management:

    • Store routes in the database for runtime flexibility.
    • Useful for multi-tenant apps, localized content, or user-specific paths.
    • Example: Redirect old URLs to new ones without code changes.
  2. Entity-Driven Controllers:

    • Bind routes to Doctrine entities to automatically resolve objects in controllers.
    • Example:
      $route->setRouteContent('AppBundle\Entity\Product:id:123');
      
      The controller receives the Product entity directly:
      public function showAction($content) {
          // $content is the Product entity with ID 123
      }
      
  3. Priority-Based Routing:

    • Chain routers with priority weights to control route resolution order.
    • Example: Dynamic routes override static routes:
      raindrop_routing:
          chain:
              routers_by_id:
                  raindrop_routing.dynamic_router: 20  # Higher priority
                  router.default: 10
      
  4. Redirects and External URLs:

    • Handle 301/302 redirects to other routes or external URIs.
    • Example:
      $redirectRoute = new Route();
      $redirectRoute->setName('old_route');
      $redirectRoute->setPath('/old-path');
      $redirectRoute->setPermanent(); // 301 status
      $redirectRoute->setController('raindrop_routing.generic_controller:redirectRouteAction');
      $redirectRoute->setRouteContent('AppBundle\Entity\Route:id:456');
      
  5. Collections in Routes:

    • Fetch multiple entities for a route (e.g., all posts in a category).
    • Example:
      $route->setRouteContent('AppBundle\Entity\Post:category_id:5');
      
      Passes an array of Post entities to the controller.

Workflows

  1. Admin Panel Integration:

    • Build a CRUD interface to manage routes via Doctrine forms.
    • Example: Let content editors define /products/{slug} paths linked to Product entities.
  2. API Route Generation:

    • Dynamically generate API endpoints (e.g., /api/v1/users/{id}) tied to database records.
    • Example:
      $apiRoute = new Route();
      $apiRoute->setName('api_user');
      $apiRoute->setPath('/api/v1/users/{id}');
      $apiRoute->setController('AppBundle:Api\User:show');
      $apiRoute->setRouteContent('AppBundle\Entity\User:id:{id}');
      
  3. Localization Support:

    • Store locale-specific routes (e.g., /es/productos/{id}) and switch dynamically.
    • Example:
      $esRoute = new Route();
      $esRoute->setName('product_es');
      $esRoute->setPath('/es/productos/{id}');
      $esRoute->setController('AppBundle:Product:show');
      $esRoute->setRouteContent('AppBundle\Entity\Product:id:{id}');
      
  4. A/B Testing Routes:

    • Dynamically toggle routes for testing (e.g., /new-homepage vs. /old-homepage).
    • Example:
      $abRoute = new Route();
      $abRoute->setName('homepage_ab');
      $abRoute->setPath('/new-homepage');
      $abRoute->setController('AppBundle:Homepage:new');
      

Integration Tips

  1. Cache Routes Aggressively:

    • Use Symfony’s router cache (cache:clear --env=prod) to improve performance.
    • Example: Cache dynamic routes in a Redis or Memcached layer.
  2. Validate Route Paths:

    • Enforce path length limits (255 chars) and regex patterns via Doctrine constraints.
    • Example:
      /**
       * @ORM\Column(length=255)
       * @Assert\Regex("/^\/[a-z0-9\-]+\/?$/", message="Invalid path format.")
       */
      private $path;
      
  3. Handle Missing Routes:

    • Implement a fallback controller for 404s:
      raindrop_routing:
          chain:
              routers_by_id:
                  raindrop_routing.dynamic_router: 10
                  router.default: 20
              fallback_controller: AppBundle:Error:notFound
      
  4. Migrate Static Routes:

    • Export existing YAML/XML routes to the database via a migration:
      // In a Doctrine migration
      $route = new Route();
      $route->setName('old_route');
      $route->setPath('/old-path');
      $route->setController('AppBundle:Old:Controller');
      $em->persist($route);
      
  5. Extend the Route Entity:

    • Add custom fields (e.g., isActive, priority) to the Route entity:
      /**
       * @ORM\Column(type="boolean")
       */
      private $isActive = true;
      
      /**
       * @ORM\Column(type="integer")
       */
      private $priority = 0;
      
  6. Use Events for Route Changes:

    • Listen to raindrop_routing.route.pre_save or raindrop_routing.route.post_save events to validate or modify routes dynamically.

Gotchas and Tips

Pitfalls

  1. Router Replacement Overhead:

    • Replacing Symfony’s default router with a chain router can introduce latency if not cached properly.
    • Fix: Always enable Symfony’s router cache (--env=prod).
  2. Entity Resolution Failures:

    • If the referenced entity (e.g., AppBundle\Entity\Product:id:123) doesn’t exist, the controller receives null.
    • Fix: Add validation in the controller:
      public function showAction($content) {
          if (!$content) {
              throw $this->createNotFoundException('Product not found.');
          }
      }
      
  3. Path Length Limits:

    • Routes are limited to 255 characters. Long slugs or nested paths may fail.
    • Fix: Use shortened paths or route aliases.
  4. Controller Signature Conflicts:

    • The $content parameter must match exactly in the controller method.
    • Fix: Use named parameters or type hints:
      public function showAction(Product $product) { ... }
      
  5. Circular Dependencies:

    • If a route references another route that references it, you’ll get an infinite loop.
    • Fix: Add a depth limit or cycle detection in the router.
  6. Missing Doctrine DBAL Type:

    • Forgetting to add Sonata\Doctrine\Types\JsonType causes serialization errors.
    • Fix: Always include:
      doctrine:
          dbal:
              types:
                  json: Sonata
      
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.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php