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

Restfabrication Bundle Laravel Package

codag/restfabrication-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require codag/restfabrication-bundle:dev-master
    

    Enable in config/bundles.php:

    Codag\RestFabricationBundle\CodagRestFabricationBundle::class => ['all' => true],
    
  2. Configure: Add to config/packages/fos_rest.yaml:

    restfabrication:
        resource_dir: '%kernel.project_dir%/src/Resources/config/resources'
        serializer:
            groups: ['api']
    
  3. First Use Case: Create a YAML resource definition in config/resources/api_user.yml:

    api_user:
        type: entity
        class: App\Entity\User
        repository: App\Repository\UserRepository
        routes:
            get: /api/users/{id}
            post: /api/users
            put: /api/users/{id}
            delete: /api/users/{id}
        serializer:
            groups: ['api']
    

    Run php bin/console restfabrication:generate:controller to scaffold a CRUD controller.


Implementation Patterns

Core Workflow

  1. Resource Definition: Define API endpoints in YAML files under resource_dir (e.g., api_user.yml). Example for nested relationships:

    api_post:
        type: entity
        class: App\Entity\Post
        routes:
            get: /api/posts/{id}
            post: /api/posts
        serializer:
            groups: ['api']
        relations:
            author:
                type: entity
                class: App\Entity\User
                serializer:
                    groups: ['api']
    
  2. Controller Generation: Generate controllers dynamically:

    php bin/console restfabrication:generate:controller --resource=api_user
    

    For custom actions, extend the generated controller:

    // src/Controller/UserController.php
    public function customAction(Request $request, $id) {
        $user = $this->getDoctrine()->getRepository(User::class)->find($id);
        return $this->handleView($this->view(['custom_data' => 'value'], 200));
    }
    
  3. Validation: Use Symfony Validator constraints in YAML:

    api_user:
        validation:
            name: NotBlank
            email: Email
    
  4. Event Listeners: Attach listeners to resource events (e.g., prePersist):

    api_user:
        listeners:
            prePersist: App\EventListener\UserPrePersistListener
    
  5. Pagination: Enable in YAML:

    api_user:
        pagination: true
    

Integration Tips

  • FOSRestBundle: Ensure FOS\RestBundle\FOSRestBundle is enabled and configured for JSON responses.
  • Doctrine: Use api serialization groups in your entities:
    #[Groups(['api'])]
    private $name;
    
  • Custom Serializers: Override default serialization by defining a custom serializer class in YAML:
    api_user:
        serializer:
            class: App\Serializer\UserSerializer
    
  • Testing: Use RestFabricationBundle's test utilities:
    $client = static::createClient();
    $client->request('GET', '/api/users/1');
    $this->assertEquals(200, $client->getResponse()->getStatusCode());
    

Gotchas and Tips

Pitfalls

  1. Outdated Bundle:

    • Last release in 2014—expect compatibility issues with modern Symfony (5.4+/6.x).
    • Workaround: Fork the repo and update dependencies (e.g., fos/rest-bundle, symfony/framework-bundle).
  2. YAML Overrides:

    • Resource definitions in YAML cannot override entity metadata (e.g., @ORM\Table).
    • Tip: Use entity listeners or custom repository methods for complex logic.
  3. Circular References:

    • Serialization groups (api) must be defined to avoid circular reference errors.
    • Fix: Add exclude_circular_reference: true in config/packages/serializer.yaml.
  4. Route Conflicts:

    • Generated routes may clash with existing ones.
    • Solution: Use _format or _locale suffixes in YAML routes:
      routes:
          get: /api/users/{id}_{_format}
      
  5. Doctrine Lifecycle Callbacks:

    • prePersist/preUpdate listeners in YAML do not trigger Doctrine events.
    • Workaround: Use Symfony event subscribers or entity lifecycle callbacks.

Debugging

  1. Generated Controllers:

    • Check generated controllers in src/Controller/ (e.g., UserController.php).
    • Tip: Use --dry-run flag to preview changes:
      php bin/console restfabrication:generate:controller --resource=api_user --dry-run
      
  2. Serialization Issues:

    • Enable debug mode and check logs for Serializer errors.
    • Tip: Use bin/console debug:serializer to inspect groups.
  3. Route Debugging:

    • Dump routes to identify mismatches:
      php bin/console debug:router | grep api_user
      

Extension Points

  1. Custom Generators:

    • Extend Codag\RestFabricationBundle\Generator\Generator to add custom templates.
    • Example: Add a generate:service command for DTOs.
  2. Dynamic Resource Loading:

    • Override Codag\RestFabricationBundle\DependencyInjection\Compiler\ResourcePass to load resources from a database.
  3. API Versioning:

    • Use Symfony’s api_platform or api route prefixes in YAML:
      routes:
          get: /api/v1/users/{id}
      
  4. Swagger/OpenAPI:

    • Integrate with nelmio/api-doc-bundle by extending the generator to include annotations:
      api_user:
          swagger:
              tags: ['Users']
              description: 'User resource'
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui