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

Route Tree Bundle Laravel Package

becklyn/route-tree-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require becklyn/route-tree-bundle
    

    Register the bundle in config/bundles.php (Laravel 5.4+) or AppKernel.php (Symfony):

    Becklyn\RouteTreeBundle\BecklynRouteTreeBundle::class => ['all' => true],
    
  2. First Use Case: Define a root route in routes.yaml (or routes.php):

    homepage:
        path: /
        options:
            tree:
                title: "Home"
    

    Then add a child route:

    about:
        path: /about
        options:
            tree:
                parent: homepage
                title: "About Us"
    
  3. Accessing the Tree: Inject the RouteTree service in a controller or Twig template:

    use Becklyn\RouteTreeBundle\Service\RouteTree;
    
    public function index(RouteTree $routeTree) {
        $tree = $routeTree->getTree();
        return view('menu', ['tree' => $tree]);
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Menu Generation: Use the tree in Twig to render a navigation menu:

    <ul>
    {% for node in tree %}
        <li>
            <a href="{{ path(node.route) }}">{{ node.title }}</a>
            {% if node.children|length > 0 %}
                <ul>
                    {% include 'partials/_menu.html.twig' with {'tree': node.children} %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
    </ul>
    
  2. Conditional Rendering: Filter nodes based on security or other logic:

    $filteredTree = $routeTree->getTree()->filter(function ($node) {
        return $node->getSecurity() === null || $this->isGranted($node->getSecurity());
    });
    
  3. Parameterized Routes: Set default parameters for child routes:

    products:
        path: /products/{category}
        options:
            tree:
                title: "Products"
                parameters: { category: "all" }
    
  4. Integration with Symfony Router: Combine with Symfony’s RouterInterface for path generation:

    $url = $router->generate($node->getRouteName(), $node->getParameters());
    

Best Practices

  • Route Naming: Use consistent, descriptive route names (e.g., admin.dashboard).
  • Tree Structure: Keep the hierarchy shallow (max 3–4 levels) for maintainability.
  • Caching: Cache the tree in production to avoid regenerating it on every request:
    $tree = $routeTree->getTree(); // Cache this in a service or controller.
    

Gotchas and Tips

Pitfalls

  1. Circular References: Ensure parent routes exist and avoid circular dependencies (e.g., ABA). Debug: Use php bin/console debug:router to verify routes.

  2. Priority Conflicts: Nodes with the same priority are sorted alphabetically by route name. Explicitly set priorities for consistent ordering:

    options:
        tree:
            priority: 10  # Higher = higher in the list
    
  3. Security Expressions: If security is not set, the node is always accessible. Omit or set to ~ to disable security checks:

    options:
        tree:
            security: ROLE_ADMIN  # Requires ROLE_ADMIN
    
  4. Parameter Overrides: Child routes inherit parent parameters but can override them. Test edge cases where parameters might conflict:

    parent_route:
        path: /parent/{id}
        options:
            tree:
                parameters: { id: 1 }
    child_route:
        path: /child
        options:
            tree:
                parent: parent_route
                parameters: { id: 2 }  # Overrides parent's default
    

Debugging

  • Dump the Tree: Use dd($routeTree->getTree()) to inspect the structure in development.
  • Check Route Existence: If a parent route is missing, the tree will silently skip the child. Validate routes with:
    php bin/console debug:router
    

Extension Points

  1. Custom Node Classes: Extend \Becklyn\RouteTreeBundle\Model\Node to add metadata:

    class CustomNode extends Node {
        public function getIcon() { return $this->icon; }
    }
    

    Override the bundle’s node.class service configuration.

  2. Tree Builders: Implement \Becklyn\RouteTreeBundle\Builder\TreeBuilderInterface for custom logic (e.g., filtering by role).

  3. Twig Extensions: Add custom filters to Twig for node manipulation:

    $twig->addFilter(new \Twig\TwigFilter('is_active', function ($node, $currentRoute) {
        return $node->getRouteName() === $currentRoute->getName();
    }));
    

Configuration Quirks

  • YAML vs. PHP: The bundle prioritizes options.tree in YAML over PHP route definitions. Ensure consistency:
    // routes.php
    Route::get('/dynamic', function () {})->options(['tree' => ['parent' => 'home']]);
    
  • Route Collection Order: Routes defined later in routes.yaml may override earlier ones. Group related routes logically.

Performance

  • Large Trees: For >100 routes, cache the tree aggressively or lazy-load children:
    $tree->getChildren($node->getRouteName()); // Load children on demand.
    
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