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

Input Hydrator Bundle Laravel Package

azjezz/input-hydrator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require azjezz/input-hydrator-bundle
    

    (Automatically registers in config/bundles.php if using Symfony Flex.)

  2. Define a DTO Class Create a simple DTO implementing AzJezz\Input\InputInterface:

    // src/Input/CreateUser.php
    namespace App\Input;
    
    use AzJezz\Input\InputInterface;
    
    final class CreateUser implements InputInterface
    {
        public string $name;
        public string $email;
    }
    
  3. Use in Controller Inject the DTO directly into a controller method:

    // src/Controller/UserController.php
    use App\Input\CreateUser;
    use Symfony\Component\HttpFoundation\Response;
    
    class UserController
    {
        public function create(CreateUser $input): Response
        {
            return new Response("Creating user: {$input->name}");
        }
    }
    
  4. Test with Request Send a request with matching input:

    curl -X POST http://your-app/user -d "name=John&email=john@example.com"
    

Key Files to Review


Implementation Patterns

1. DTO Design Patterns

  • Type Safety: Properties must match request data types (e.g., string for text fields).
  • Validation: Use PHP type hints + InputInterface for implicit validation.
  • Nested Objects: Support nested DTOs by referencing them in properties:
    public NestedDto $address; // Automatically hydrates from `address[street]` etc.
    

2. Request Integration

  • Automatic Binding: Works with Symfony’s RequestStack and ParameterBagInterface.
  • Request Sources:
    • Form data (POST/PUT).
    • Query params (GET).
    • JSON payloads (if using Content-Type: application/json).
  • Custom Sources: Extend AzJezz\Input\Hydrator\HydratorInterface for custom input sources (e.g., headers).

3. Workflow Integration

  • Controller Layer:
    public function update(UpdateUser $input, UserRepository $repo): Response
    {
        $user = $repo->find($input->id);
        $user->update($input); // Pass DTO to service layer
    }
    
  • Service Layer: Accept DTOs as method parameters for clean separation:
    public function process(CreateUser $input): void
    {
        // Business logic using $input->name, $input->email
    }
    
  • Form Handling: Pair with Symfony Forms for complex validation:
    public function store(CreateUser $input, ValidatorInterface $validator): Response
    {
        $errors = $validator->validate($input);
        // Handle errors...
    }
    

4. API-First Development

  • OpenAPI/Swagger: Document DTOs as request bodies:
    # config/packages/nelmio_api_doc.yaml
    components:
      schemas:
        CreateUser:
          type: object
          properties:
            name: { type: string }
            email: { type: string }
    
  • API Platform: Use with @ApiResource for automatic DTO hydration.

Gotchas and Tips

Common Pitfalls

  1. Type Mismatches:

    • Error: BadRequestHttpException if string property receives array.
    • Fix: Ensure request data matches DTO property types. Use ?string for nullable fields.
  2. Missing Required Fields:

    • Error: BadRequestHttpException for undefined properties.
    • Fix: Mark properties as public (required) or use ?Type for optional fields.
  3. Nested Object Hydration:

    • Issue: Nested DTOs must have matching request keys (e.g., address.street for public Address $address).
    • Fix: Use dot notation in request data or configure custom hydrators.
  4. Case Sensitivity:

    • Issue: Request keys are case-sensitive (e.g., Name vs name).
    • Fix: Standardize on snake_case or camelCase in DTOs and requests.

Debugging Tips

  • Enable Debug Mode: Symfony’s debug:router and debug:container help inspect resolvers.
  • Check Hydrator Events: Listen for azjezz.input.hydrator.hydrate events to log hydration steps:
    $eventDispatcher->addListener('azjezz.input.hydrator.hydrate', function ($event) {
        error_log('Hydrating: ' . print_r($event->getInput(), true));
    });
    
  • Custom Exceptions: Extend AzJezz\Input\Exception\HydrationException for domain-specific errors.

Extension Points

  1. Custom Hydrators:

    // src/Hydrator/CustomHydrator.php
    use AzJezz\Input\Hydrator\HydratorInterface;
    
    class CustomHydrator implements HydratorInterface
    {
        public function hydrate(array $data, object $input): void
        {
            $input->customField = $data['custom_key'] ?? null;
        }
    }
    

    Register in services:

    # config/services.yaml
    AzJezz\Input\HydratorBundle\:
        arguments:
            $hydrators: ['@custom_hydrator']
    
  2. Override Default Behavior:

    • Disable strict mode (allow missing fields):
      # config/packages/azjezz_input_hydrator.yaml
      azjezz_input_hydrator:
          strict: false
      
    • Customize error responses:
      $eventDispatcher->addListener('azjezz.input.hydrator.error', function ($event) {
          $event->setResponse(new JsonResponse(['error' => 'Invalid input'], 400));
      });
      
  3. Performance:

    • Cache DTO classes if used frequently (Symfony’s autowiring handles this by default).
    • Avoid deep nesting in DTOs to reduce hydration overhead.

Configuration Quirks

  • Bundle Auto-Registration: Works with Symfony Flex but may need manual bundles.php addition for older setups.
  • Priority in Resolvers: Ensure AzJezz\Input\HydratorBundle\DependencyInjection\Compiler\HydratorPass runs early in the container compilation.
  • PHP 8 Features: Leverage named arguments in DTO constructors if extending the hydrator logic.
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours