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

Restgeneratorbundle Laravel Package

chrl/restgeneratorbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies Run:

    composer require voryx/restgeneratorbundle dev-master
    

    Ensure FOSRestBundle, JMSSerializerBundle, and NelmioCorsBundle are also installed (required).

  2. Register the Bundle Add to config/bundles.php:

    Voryx\RESTGeneratorBundle\VoryxRESTGeneratorBundle::class => ['all' => true],
    
  3. Configure Required Bundles Update config/packages/fos_rest.yaml:

    framework:
        csrf_protection: false  # Disable for public APIs
    fos_rest:
        routing_loader:
            default_format: json
        view:
            view_response_listener: force
    
  4. Generate a REST Controller Run the generator command for an entity (e.g., App\Entity\Post):

    php bin/console voryx:rest:generate App\Entity\Post
    

    This creates a controller with CRUD actions (GET, POST, PUT, DELETE) in src/Controller/.

  5. Route the Controller Ensure your routes are defined in config/routes.yaml or via annotations.


First Use Case

Generate a REST API for a User entity:

php bin/console voryx:rest:generate App\Entity\User

This auto-generates:

  • Controller with CRUD methods.
  • Serialization/deserialization logic (via JMS).
  • CORS headers (via NelmioCorsBundle).

Test with:

curl -X GET http://your-app/api/users -H "Accept: application/json"

Implementation Patterns

Workflow: Rapid API Prototyping

  1. Entity-First Development Define your Doctrine entity (e.g., Product):

    // src/Entity/Product.php
    #[ORM\Entity]
    class Product {
        #[ORM\Id, ORM\GeneratedValue]
        private ?int $id = null;
    
        #[ORM\Column]
        private string $name;
    }
    

    Generate the REST layer immediately:

    php bin/console voryx:rest:generate App\Entity\Product
    
  2. Customizing Actions Override generated methods in the controller:

    // src/Controller/ProductController.php
    public function postAction(Request $request) {
        $data = $this->get('request')->request->all();
        // Custom validation/logic
        return parent::postAction($request);
    }
    
  3. Nested Resources For nested routes (e.g., /users/{id}/posts), extend the generator or manually define routes in routing.yml:

    app_user_post:
        path: /users/{user_id}/posts
        defaults: { _controller: App\Controller\PostController::indexAction }
    
  4. Pagination Use FOSRestBundle's pagination (configure in fos_rest.yaml):

    pagination:
        max_per_page: 30
        persistent_max_per_page: true
    
  5. Filtering/Sorting Leverage FOSRestBundle's query parameters:

    curl http://your-app/api/users?filter[name]=John&sort[createdAt]=desc
    

Integration Tips

  • Authentication: Pair with LexikJWTAuthenticationBundle or FOSUserBundle for secured endpoints. Example:
    # config/packages/security.yaml
    access_control:
        - { path: ^/api/users, roles: ROLE_USER }
    
  • Validation: Use Symfony Validator constraints in your entity:
    #[Assert\NotBlank]
    private string $name;
    
  • Testing: Use Symfony Panther or Guzzle to test generated endpoints:
    $client = static::createClient();
    $response = $client->request('GET', '/api/users');
    $this->assertResponseIsSuccessful();
    

Gotchas and Tips

Pitfalls

  1. CSRF Protection

    • Issue: Disabling csrf_protection globally may expose your API to CSRF attacks.
    • Fix: Use fos_rest.view.disable_csrf_role to restrict CSRF bypass to specific roles:
      fos_rest:
          disable_csrf_role: ROLE_API_USER
      
  2. Overwriting Generated Code

    • Issue: Regenerating the controller overwrites custom logic.
    • Fix: Extend the generated controller instead of modifying it directly:
      // src/Controller/ProductController.php
      class ProductController extends GeneratedProductController {
          public function customMethod() { ... }
      }
      
  3. CORS Misconfiguration

    • Issue: NelmioCorsBundle may block requests if not configured properly.
    • Fix: Explicitly allow methods/headers:
      nelmio_cors:
          paths:
              '^/api/':
                  allow_origin: ['*']
                  allow_methods: ['GET', 'POST', 'PUT', 'DELETE']
                  allow_headers: ['Content-Type', 'Authorization']
      
  4. Serialization Errors

    • Issue: JMS Serializer may fail on circular references or unsupported types.
    • Fix: Configure handlers in config/packages/jms_serializer.yaml:
      handlers:
          DateTimeHandler: ~
      
  5. Route Conflicts

    • Issue: Generated routes may clash with existing ones.
    • Fix: Prefix routes in routing.yml:
      app_rest:
          resource: "@VoryxRESTGeneratorBundle/Resources/config/routing.yml"
          prefix: /api
      

Debugging Tips

  1. Check Generated Code Inspect the generated controller at src/Controller/ to verify logic.

  2. Enable Debug Mode Set APP_DEBUG=true in .env to see detailed errors.

  3. Log Requests Use Symfony’s profiler (/_profiler) or add a listener:

    // src/EventListener/RequestLogger.php
    public function onKernelRequest(GetResponseEvent $event) {
        error_log($event->getRequest()->getContent());
    }
    
  4. Validate Entities Use Symfony’s validator component to debug entity issues:

    $validator = $this->get('validator');
    $errors = $validator->validate($entity);
    

Extension Points

  1. Custom Actions Add new methods to the generated controller and route them manually:

    # config/routes.yaml
    app_product_export:
        path: /api/products/export
        methods: GET
        defaults: { _controller: App\Controller\ProductController::exportAction }
    
  2. Dynamic Routing Use FOSRestBundle's dynamic routing to support custom formats:

    fos_rest:
        routing_loader:
            default_format: json
            include_format: true
    
  3. Event Subscribers Hook into lifecycle events (e.g., prePersist) via Doctrine listeners:

    // src/EventListener/ProductListener.php
    #[ORM\HasLifecycleCallbacks]
    class Product {
        #[ORM\PrePersist]
        public function setCreatedAt() {
            $this->createdAt = new \DateTime();
        }
    }
    
  4. API Documentation Integrate with NelmioApiDocBundle for Swagger/OpenAPI docs:

    nelmio_api_doc:
        routes:
            path: /api/doc
    
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