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

Dto Laravel Package

codememory/dto

Auto-hydrate PHP/Symfony DTOs from request/array data using rules and decorators. Supports name conversion (e.g., snake_case), enum casting via attributes, and event hooks during processing. Build a manager with caching and reflection for fast mapping.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • DTO Pattern Alignment: The package aligns well with the Data Transfer Object (DTO) pattern, enabling structured data hydration from unstructured sources (e.g., HTTP requests, APIs, or arrays). This is particularly useful in Laravel for request validation, API payload processing, and domain layer abstraction.
  • Symfony Compatibility: While designed for Symfony, the package is framework-agnostic and can be leveraged in Laravel for decoupled data transformation without tight coupling to Symfony’s ecosystem.
  • Attribute-Based Decorators: The use of PHP attributes (decorators) for metadata-driven processing is a modern approach, though Laravel’s native attribute support (via #[Attribute]) requires PHP 8.0+. This could introduce minor version compatibility risks if using older Laravel versions.
  • Event-Driven Validation: The event system for validation (e.g., AfterProcessedTypeDecoratorsEvent) allows for custom validation logic, which can integrate with Laravel’s validation pipeline (e.g., Illuminate\Validation\Validator).

Integration Feasibility

  • Laravel Request Handling: The package can replace or supplement Laravel’s built-in Illuminate\Http\Request validation by providing fine-grained control over DTO hydration (e.g., nested objects, enum mapping, custom type casting).
  • API Resource Layer: Useful for API responses where structured DTOs are transformed from database models or services, reducing boilerplate in App\Http\Resources.
  • Form Requests: Can enhance Laravel’s FormRequest classes by adding decorator-based validation (e.g., @SymfonyValidation) without mixing concerns with Laravel’s validation rules.
  • Database Hydration: Could streamline Eloquent model population from API payloads or external data sources (e.g., CSV imports) by leveraging decorators for type conversion, default values, and constraints.

Technical Risk

  • No Optional Parameters: The package does not support optional fields, which may conflict with Laravel’s flexible request handling (e.g., partial updates in PATCH requests). Workarounds (e.g., default values via decorators) would be needed.
  • Symfony Dependencies: While the core is framework-agnostic, Symfony-specific decorators (e.g., SymfonyValidation) introduce indirect dependencies. A Laravel TPM must evaluate whether these are acceptable or if alternatives (e.g., Laravel’s Illuminate\Validation) should be prioritized.
  • Performance Overhead: The reflection-heavy nature of the package (via ReflectorManager) could introduce runtime latency if overused. Caching (via FilesystemAdapter) mitigates this but adds storage dependencies.
  • Error Handling: The package throws exceptions on validation failures, which may not align with Laravel’s graceful error handling (e.g., returning HTTP 422 with validation errors). Custom event listeners would be required to adapt this behavior.
  • Lack of Adoption: With 0 dependents and 1 star, the package’s long-term viability is uncertain. A TPM should assess whether the maintenance burden outweighs the benefits.

Key Questions

  1. Use Case Fit:

    • Does this package solve a specific pain point in Laravel (e.g., complex nested DTO hydration, enum handling, or validation consolidation) that isn’t already addressed by Laravel’s built-in tools?
    • Would it reduce boilerplate in API resources, form requests, or service layers?
  2. Alternatives:

    • How does this compare to Laravel’s native validation, Spatie’s Data Transfer Objects, or API Platform’s DTO tools?
    • Are the Symfony-specific decorators (e.g., SymfonyValidation) a blocker for adoption?
  3. Maintenance:

    • Is the package’s MIT license and active development (last release: 2025) sufficient for production use?
    • Would the team need to fork or extend the package to fill gaps (e.g., optional fields, Laravel-specific integrations)?
  4. Performance:

    • How would the reflection overhead scale in high-throughput APIs?
    • Are there caching strategies to optimize repeated DTO hydration?
  5. Team Skills:

    • Does the team have experience with attribute-based programming and event-driven validation?
    • Is there buy-in to adopt a non-Laravel-native package for DTOs?

Integration Approach

Stack Fit

  • Laravel 9+/PHP 8.0+: The package requires PHP 8.0+ (for attributes) and works best with Laravel’s modern features (e.g., #[Attribute], Illuminate\Validation).
  • Symfony Bridge: If using Symfony-specific decorators (e.g., SymfonyValidation), ensure Symfony’s validator component is installed (symfony/validator). For pure Laravel, these can be replaced with custom decorators.
  • API-Centric Projects: Ideal for REST/GraphQL APIs where DTOs are used for request/response transformation.
  • Legacy Systems: Less suitable for monolithic Laravel apps with simple validation needs, as the overhead may not justify the benefits.

Migration Path

  1. Pilot Phase:
    • Start with non-critical DTOs (e.g., API responses, internal service contracts) to test integration.
    • Replace manual array-to-object mapping with hydrate() calls.
  2. Decorator Adoption:
    • Replace Laravel’s #[Rule] or #[Validated] with #[Property\SymfonyValidation] (or custom decorators).
    • Example:
      // Before (Laravel Form Request)
      public function rules(): array { return ['email' => 'required|email']; }
      
      // After (DTO with Decorator)
      #[Property\SymfonyValidation([
          new Assert\NotBlank(),
          new Assert\Email()
      ])]
      public string $email;
      
  3. Event Listeners:
    • Replace Laravel’s FormRequest::failedValidation() with custom AfterProcessedTypeDecoratorsEvent listeners for validation.
    • Example:
      $eventDispatcher->addListener(
          AfterProcessedTypeDecoratorsEvent::class,
          fn($event) => throw_if_invalid($event->data)
      );
      
  4. Request Handling:
    • Extend Laravel’s Illuminate\Http\Request to use the DTO manager:
      public function hydrateRequest(array $data): MyDto {
          return $this->dtoManager->hydrate(MyDto::class, $data);
      }
      

Compatibility

  • Laravel Services: The DataTransferObjectManager can be registered as a Laravel service provider:
    public function register(): void {
        $this->app->singleton(DataTransferObjectManager::class, fn($app) => new DataTransferObjectManager(
            new ReflectorManager(new FilesystemAdapter('codememory')),
            // ... other dependencies
        ));
    }
    
  • Validation Integration:
    • Use Symfony’s validator alongside Laravel’s Illuminate\Validation for hybrid validation.
    • Or, replace Symfony decorators with Laravel-specific ones (e.g., #[Property\LaravelValidation]).
  • Testing:
    • The package’s event system allows for mockable validation logic, improving test isolation.

Sequencing

  1. Phase 1: Core Hydration
    • Replace manual new MyDto($data) with hydrate(MyDto::class, $data).
    • Focus on simple DTOs (no validation).
  2. Phase 2: Decorators
    • Add type conversion decorators (ToEnum, ToDateTime).
    • Replace basic Laravel validation with decorator-based rules.
  3. Phase 3: Validation Pipeline
    • Integrate event listeners for validation.
    • Migrate from FormRequest to DTO + event-driven validation.
  4. Phase 4: Full Adoption
    • Extend to API resources, command buses, and database imports.
    • Deprecate legacy manual mapping code.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Decorators centralize validation logic, reducing duplicate rules.
    • Consistent Hydration: Standardized hydrate() method across the codebase.
    • Extensible: Custom decorators can be added without modifying core logic.
  • Cons:
    • Reflection Complexity: Debugging reflection-based hydration may be harder than manual mapping.
    • Dependency Management: Symfony components (if used) add composer dependency overhead.
    • Optional Fields Workaround: Requires custom decorators or pre-processing to handle partial updates.

Support

  • Learning Curve:
    • Team must learn attribute-based decorators and event-driven validation.
    • Documentation is minimal (1-star package), so internal docs or workshops may be needed.
  • Debugging:
    • Validation errors may be less intuitive than Laravel’s
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor