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

Rest Routing Bundle Laravel Package

handcraftedinthealps/rest-routing-bundle

Symfony bundle that restores FOSRestBundle-style automatic REST route generation. Supports format options and method/name prefixing, and includes a command to dump/convert type: rest routes into standard Symfony routes for migration or opt-out.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require handcraftedinthealps/rest-routing-bundle
    

    Enable the bundle in config/bundles.php:

    HandcraftedInTheAlps\RestRoutingBundle\RestRoutingBundle::class => ['all' => true],
    
  2. Configure in config/packages/handcraftedinthealps_rest_routing.yaml:

    handcraftedinthealps_rest_routing:
        routing_loader:
            default_format: 'json'
            prefix_methods: true
            include_format: true
    
  3. Annotate a Controller:

    use HandcraftedInTheAlps\RestRoutingBundle\Controller\Annotations\RouteResource;
    use HandcraftedInTheAlps\RestRoutingBundle\Routing\ClassResourceInterface;
    
    #[RouteResource]
    class PostController implements ClassResourceInterface
    {
        // Methods will auto-generate routes (e.g., `getItem`, `cudCollection`)
    }
    
  4. Test by accessing endpoints (e.g., GET /api/posts for getCollection).


First Use Case: Migrating from FOSRestBundle

Replace FOS annotations with the bundle’s equivalents:

- use FOS\RestBundle\Controller\Annotations\RouteResource;
+ use HandcraftedInTheAlps\RestRoutingBundle\Controller\Annotations\RouteResource;

Run the migration command to dump routes:

bin/console fos:rest:routing:dump-symfony-routes

Implementation Patterns

1. Controller Annotations

Use annotations to define RESTful routes:

#[RouteResource("api", namePrefix: "api_")]
class UserController implements ClassResourceInterface
{
    #[NoRoute] // Exclude from auto-routing
    public function customAction(): Response { ... }

    #[Version("v1")] // Route under `/api/v1/users`
    public function getCollection(): Response { ... }
}

2. Route Customization

Override defaults via annotations:

#[RouteResource(
    collectionOperations: ["get" => false], // Disable GET /users
    itemOperations: ["put" => ["method" => "PATCH"]] // Customize PUT
)]
class ProductController implements ClassResourceInterface { ... }

3. Ignoring Classes

Exclude specific controllers from auto-routing:

# config/packages/handcraftedinthealps_rest_routing.yaml
handcraftedinthealps_rest_routing:
    routing_loader:
        ignored_classes:
            - App\Controller\Admin\DashboardController

4. Integration with FOSRestBundle

If using both bundles, ensure configurations align:

# Merge formats if needed
handcraftedinthealps_rest_routing:
    routing_loader:
        formats:
            json: true
            xml: true

5. Testing Routes

Use Symfony’s RouterInterface or UrlGeneratorInterface:

$url = $this->router->generate('api_post_collection_get');
$this->assertEquals('/api/posts', $url);

Gotchas and Tips

Pitfalls

  1. Annotation Conflicts:

    • Avoid mixing @Route (Symfony) with @RouteResource. Use @NoRoute to exclude methods.
    • Fix: Ensure all REST methods implement ClassResourceInterface.
  2. Route Naming Collisions:

    • Prefixes (namePrefix) must be unique across controllers.
    • Fix: Use descriptive prefixes (e.g., api_user_, admin_product_).
  3. Deprecated FOSRestBundle:

    • The bundle is a drop-in replacement but lacks some FOS features (e.g., format negotiation).
    • Workaround: Use Symfony’s RequestContext or middleware for formats.
  4. PHP 8+ Deprecations:

    • Nullable objects (e.g., ?Response) may trigger warnings.
    • Fix: Update to >=1.1.2 or type-hint strictly (e.g., Response).

Debugging Tips

  1. Dump Generated Routes:

    bin/console debug:router | grep "api_"
    

    Or use the dump-symfony-routes command to preview routes before migration.

  2. Check Annotations:

    • Run bin/console debug:container --tag="rest.controller" to verify annotated controllers.
  3. Log Route Loading: Enable debug mode to log route generation:

    # config/packages/dev/handcraftedinthealps_rest_routing.yaml
    handcraftedinthealps_rest_routing:
        routing_loader:
            debug: true
    

Extension Points

  1. Custom Route Naming: Override RestActionReader to modify route names dynamically:

    class CustomActionReader extends RestActionReader
    {
        protected function getRouteName(string $namePrefix, string $methodName): string
        {
            return $namePrefix . '_custom_' . $methodName;
        }
    }
    

    Register as a service:

    services:
        HandcraftedInTheAlps\RestRoutingBundle\Routing\RestActionReader:
            class: App\Routing\CustomActionReader
    
  2. Add Route Attributes: Extend RouteResource to support custom attributes:

    #[Attribute]
    class Cacheable
    {
        public function __construct(public bool $enabled = true) {}
    }
    
    #[RouteResource]
    #[Cacheable]
    class PostController { ... }
    

    Hook: Implement a compiler pass to process attributes.

  3. Conditional Route Loading: Use Symfony’s CompilerPass to load routes only in specific environments:

    public function process(ConfigCache $cache)
    {
        if (!$cache->isFresh()) {
            $this->container->get('router')->getRouteCollection()->addCollection(
                $this->container->get('rest_routing.loader')->load(__DIR__.'/routes.yaml')
            );
        }
    }
    

Performance Considerations

  • Cache Routes: The bundle caches routes by default. Clear cache after changes:
    bin/console cache:clear
    
  • Avoid Over-Annotation: Use @NoRoute for non-REST methods to reduce parsing overhead.
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/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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
agtp/mod-php
splash/sonata-admin