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 Bundle Laravel Package

dontdrinkandroot/rest-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dontdrinkandroot/rest-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        DontDrinkAndRoot\RestBundle\DontDrinkAndRootRestBundle::class => ['all' => true],
    ];
    
  2. Enable REST Endpoints: Configure routing in config/routes.yaml:

    dont_drink_and_root_rest:
        resource: "@DontDrinkAndRootRestBundle/Resources/config/routing.yml"
        prefix: /api
    
  3. First Use Case: Annotate a Doctrine entity (e.g., src/Entity/User.php) with @Rest\Resource:

    use DontDrinkAndRoot\RestBundle\Annotation\Rest;
    
    /**
     * @Rest\Resource()
     */
    class User {}
    

    Access via /api/user (GET, POST, PUT, DELETE).


Implementation Patterns

Workflows

  1. CRUD Operations: The bundle auto-generates REST endpoints for annotated entities. No manual controller needed. Example:

    /**
     * @Rest\Resource(
     *     collectionOperations={"get", "post"},
     *     itemOperations={"get", "put", "delete"}
     * )
     */
    class Product {}
    
    • GET /api/product → List all products.
    • POST /api/product → Create a product.
    • GET /api/product/{id} → Fetch a product.
    • PUT /api/product/{id} → Update a product.
  2. Customization: Override default behavior by extending the bundle’s services or creating custom controllers. Example: Add a search operation:

    # config/routes.yaml
    dont_drink_and_root_rest.search:
        path: /api/user/search
        methods: GET
        defaults: { _controller: App\Controller\UserController::searchAction }
    
  3. Serialization: Use JMS Serializer (bundled by default) to control output. Configure in config/packages/jms_serializer.yaml:

    jms_serializer:
        metadata:
            directories:
                App:
                    namespace_prefix: "App\\Entity"
                    path: "%kernel.project_dir%/config/serializer"
    
  4. Authentication: Secure endpoints with Symfony’s security component. Example in config/packages/security.yaml:

    access_control:
        - { path: ^/api/user, roles: ROLE_USER }
    

Integration Tips

  • Doctrine Events: Listen to prePersist, preUpdate, etc., to modify data before serialization.
  • Validation: Use Symfony Validator constraints (e.g., @Assert\NotBlank) on entity properties.
  • Pagination: Implement KnpPaginator or manually paginate results in custom controllers.

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies: The bundle was last updated in 2016 and may conflict with modern Symfony/Laravel (if using via bridge). Test thoroughly with your stack.

    • Workaround: Fork and update dependencies (e.g., symfony/dependency-injection to ^5.0).
  2. No Laravel Support: This is a Symfony bundle, not Laravel. For Laravel, consider:

  3. Limited Documentation: Assumptions are made about Symfony’s internals (e.g., routing, DI). Refer to Symfony’s docs for edge cases.

  4. Serialization Conflicts: JMS Serializer may not handle circular references or complex types out-of-the-box. Configure custom handlers in config/packages/jms_serializer.yaml:

    handlers:
        App\Entity\ComplexType:
            strategy: skip
    

Debugging

  1. Check Annotations: Ensure @Rest\Resource is correctly placed. Use php app/console debug:container DontDrinkAndRoot\RestBundle\Annotation\Rest to verify registration.

  2. Routing Debug: Run php app/console debug:router to confirm REST routes are loaded.

  3. Logs: Enable debug mode (APP_ENV=dev) and check var/log/dev.log for serialization or Doctrine errors.

Extension Points

  1. Custom Controllers: Override default behavior by creating a controller and referencing it in collectionOperations/itemOperations:

    /**
     * @Rest\Resource(
     *     itemOperations={
     *         "custom" = { "method" = "GET", "path" = "/api/user/{id}/custom", "controller" = "App\Controller\UserController::customAction" }
     *     }
     * )
     */
    class User {}
    
  2. Event Listeners: Subscribe to rest.pre_serialization or rest.post_deserialization events to modify payloads:

    // src/EventListener/CustomRestListener.php
    class CustomRestListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                'rest.pre_serialization' => 'onPreSerialization',
            ];
        }
        public function onPreSerialization(GetResponseEvent $event) { ... }
    }
    
  3. Dynamic Routing: Use Symfony’s ParameterBag to dynamically adjust routes based on environment or user roles.

Performance Tips

  • Caching: Cache serialized responses with Symfony’s HTTP cache or Varnish.
  • Eager-Loading: Use Doctrine’s fetch="EAGER" or DQL JOIN to avoid N+1 queries in nested entities.

```markdown
---
**Note for Laravel Developers**:
While this bundle is Symfony-specific, its core concepts (auto-generated REST endpoints, JMS Serializer, Doctrine integration) align with Laravel’s ecosystem. For Laravel, consider:
- **Laravel: [Laravel API Resources](https://laravel.com/docs/eloquent-resources)** for serialization.
- **Laravel: [Dingo API](https://github.com/dingo/api)** for REST routing.
- **Laravel: [Fractal](https://fractal.thephpleague.com/)** for complex transformations.
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime