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

azjezz/input-hydrator

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • DTO Hydration Pattern: The package aligns well with clean architecture and hexagonal design principles by decoupling request parsing from business logic. It enforces immutable DTOs (Data Transfer Objects) for input validation and transformation, reducing boilerplate in controllers.
  • Laravel Ecosystem Synergy: Works seamlessly with Laravel’s request lifecycle (e.g., Illuminate\Http\Request), validation (Illuminate\Validation), and form requests. Complements packages like spatie/laravel-data or vinkla/hashids for structured input handling.
  • Domain-Driven Design (DDD) Fit: Ideal for bounded contexts where input normalization is critical (e.g., APIs, microservices). Hydrators can be scoped to aggregates or use cases.
  • Alternatives Comparison:
    • Pros: Explicit DTO mapping, type safety (via PHP 7.4+ typed properties), and separation of concerns.
    • Cons: Less flexible than dynamic hydrators (e.g., symfony/serializer); requires upfront DTO definition.

Integration Feasibility

  • Laravel-Specific Hooks:
    • Integrates with Illuminate\Foundation\Http\FormRequest via hydrate() method.
    • Can replace manual Request->only()/except() calls or array_merge() hacks.
    • Works with API resources (Illuminate\Http\Resources\Json\JsonResource) for output hydration (though the package focuses on input).
  • Non-Laravel PHP:
    • PSR-7/PSR-15 Compatibility: Can hydrate from Psr\Http\Message\ServerRequestInterface with minor adapter layer (e.g., zend-expressive).
    • Symfony DI: Supports constructor injection for hydrators, but Laravel’s service container may require binding adjustments.
  • Database/ORM:
    • Eloquent: No direct integration, but hydrators can prep data for mass assignment or query scopes.
    • Query Builder: Useful for sanitizing input before where() clauses.

Technical Risk

  • Deprecation Risk:
    • Last release in 2020 (PHP 7.4 era). Risk of PHP 8.x incompatibilities (e.g., named arguments, union types).
    • Mitigation: Fork or wrap in a compatibility layer (e.g., azjezz/input-hydrator-legacy).
  • Performance Overhead:
    • Reflection-based hydration may add ~5–10ms per request in high-throughput APIs.
    • Mitigation: Cache hydrator instances or use static::hydrate() for singleton patterns.
  • Validation Duplication:
    • Hydrators do not validate; must pair with Laravel’s validation or libraries like respect/validation.
    • Risk: Inconsistent validation logic if hydrators and form requests diverge.
  • Testing Complexity:
    • Hydrators introduce new test surfaces (e.g., edge cases in nested DTOs).
    • Solution: Use PHPUnit data providers for DTO test matrices.

Key Questions

  1. PHP Version Support:
    • Is PHP 8.1+ support critical? If yes, will a fork or polyfill be needed?
  2. DTO Complexity:
    • Are DTOs flat (simple properties) or nested (collections, recursive structures)? Complex DTOs may need custom hydrator logic.
  3. Validation Strategy:
    • How will validation (e.g., Laravel’s FormRequest) interact with hydrators? Will hydrators pre-filter data?
  4. Performance SLAs:
    • Can the ~5–10ms overhead be tolerated, or is a lighter alternative (e.g., manual mapping) preferred?
  5. Long-Term Maintenance:
    • Is the team willing to maintain a fork, or should this be a short-term migration tool?

Integration Approach

Stack Fit

Component Fit Level Notes
Laravel Controllers ✅ High Replaces Request->input() with Hydrator::hydrate($request)
Form Requests ✅ High Extend FormRequest to hydrate DTOs in authorize() or rules()
API Resources ⚠️ Medium Not primary use case, but can hydrate input for resource creation
Queues/Jobs ✅ High Hydrate DTOs from serialized payloads (e.g., JobPayload::fromRequest())
CLI Artisan Commands ⚠️ Low Overkill for CLI; manual parsing may suffice
Livewire/Inertia ❌ No Frontend frameworks handle input differently; hydrators add no value

Migration Path

  1. Phase 1: Pilot DTOs
    • Start with 1–2 high-value endpoints (e.g., user registration, payment processing).
    • Define DTOs for input (e.g., CreateUserRequestDTO) and hydrate in controllers:
      public function store(CreateUserRequest $request) {
          $dto = CreateUserRequestDTO::hydrate($request);
          // Use $dto->email, $dto->password (immutable, validated)
      }
      
  2. Phase 2: Form Request Integration
    • Extend FormRequest to hydrate DTOs in withValidator():
      public function withValidator() {
          $dto = $this->hydrate(CreateUserRequestDTO::class);
          $this->validator->after(function ($validator) use ($dto) {
              // Post-hydration validation
          });
      }
      
  3. Phase 3: Replace Manual Parsing
    • Refactor controllers to eliminate Request->only()/except() calls.
    • Use hydrators for query params, headers, and payloads (e.g., webhooks).
  4. Phase 4: Testing & Optimization
    • Add DTO hydration tests (e.g., HydrateUserRequestTest).
    • Profile performance; cache hydrators if needed.

Compatibility

  • Laravel Versions:
    • Tested on Laravel 6–8.x; may need tweaks for Laravel 9+ (PHP 8.0+).
    • Solution: Use laravel/framework version constraints in composer.json.
  • PHP Extensions:
    • Requires PHP 7.4+ (for typed properties). PHP 8.1+ may need adjustments.
  • Dependencies:
    • No hard dependencies beyond PHP core; conflicts unlikely.
  • Database:
    • No direct DB integration, but hydrators can sanitize input for queries:
      $dto = SearchQueryDTO::hydrate($request);
      User::where('name', 'like', "%{$dto->query}%")->get();
      

Sequencing

  1. Pre-Migration:
    • Audit controllers for manual input parsing.
    • Define DTO contracts (e.g., CreateOrderRequestDTO).
  2. Parallel Run:
    • Run old and new code side-by-side for critical paths.
  3. Post-Migration:
    • Deprecate legacy parsing logic.
    • Add hydrator-specific tests (e.g., invalid input handling).

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Eliminates repetitive Request->input() calls.
    • Type Safety: Catches errors at compile time (PHP 7.4+).
    • Centralized Logic: DTOs act as a single source of truth for input shapes.
  • Cons:
    • DTO Bloat: Overkill for simple APIs (e.g., CRUD with 2–3 fields).
    • Refactoring Cost: Existing controllers may need significant changes.
  • Long-Term:
    • Easier to add/remove fields via DTOs than scattered Request->only() calls.
    • Supports backward compatibility via DTO versioning (e.g., v1, v2).

Support

  • Debugging:
    • Clearer Error Messages: Hydration failures (e.g., missing fields) are explicit.
    • Tooling: Use Xdebug to inspect DTOs during debugging.
  • Documentation:
    • Self-Documenting: DTOs serve as API contracts (e.g., OpenAPI/Swagger).
    • Example: Generate DTO docs via phpdoc or custom scripts.
  • Community:
    • Limited Ecosystem: Few tutorials; may require internal docs.
    • Alternatives: Consider spatie/laravel-data if community support is a priority.

Scaling

  • Performance:
    • Cold Start: Reflection overhead on first hydrate (~10ms).
    • Warm Start: Cached instances reduce overhead to ~1ms.
    • High Load: Consider pre-hydrating common DTOs
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