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

Request Dto Mapper Bundle Laravel Package

artyuum/request-dto-mapper-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Require the package via Composer:
    composer require vendor/package-name
    
  2. Enable the Bundle: Register the bundle in config/app.php under the extra.bundles key.
  3. Annotate a Controller: Use the new PHP attribute to configure DTOs directly on controller methods:
    use Vendor\Package\Attribute\Dto;
    
    class UserController extends Controller
    {
        #[Dto]
        public function store(Request $request)
        {
            // DTO validation and binding handled automatically
        }
    }
    
  4. Define a DTO Class: Create a class with validation rules (e.g., using Symfony Validator):
    use Symfony\Component\Validator\Constraints as Assert;
    
    class CreateUserDto
    {
        #[Assert\NotBlank]
        public string $name;
    
        #[Assert\Email]
        public string $email;
    }
    

First Use Case

Convert a controller action to use DTOs for validation and type safety:

#[Dto(CreateUserDto::class)]
public function store(Request $request, CreateUserDto $dto)
{
    // $dto is automatically validated and populated
    $user = User::create($dto->toArray());
    return response()->json($user);
}

Implementation Patterns

Controller Integration

  • Attribute-Based Configuration: Prefer the new #[Dto] attribute over manual configuration for simplicity.
  • Event-Driven Workflow: Leverage PostDtoValidationEvent to customize behavior post-validation:
    event(new PostDtoValidationEvent($dto, $request));
    
  • Request Data Extraction: Use flexible extraction methods (e.g., nested arrays, custom sources):
    #[Dto(CreateUserDto::class, source: 'data.user')]
    public function store(Request $request)
    

Validation and Error Handling

  • Store Violations: Access validation errors via request attributes:
    $errors = $request->get('dto_validation_errors', []);
    
  • Custom Constraints: Extend DTO classes with custom Symfony constraints or validation logic.

Advanced Configuration

  • Global Defaults: Set default options in config/packages/vendor_package.php:
    'default_options' => [
        'throw_exceptions' => false,
        'validator' => 'symfony', // or 'laravel'
    ],
    
  • Per-Controller Overrides: Override defaults per method:
    #[Dto(CreateUserDto::class, options: ['throw_exceptions' => true])]
    

Testing

  • Unit Tests: Mock kernel.controller_arguments event for testing:
    $this->app->dispatch(new ControllerArgumentsEvent($request, $controller, $method));
    

Gotchas and Tips

Breaking Changes

  • Argument Resolver Removal: The package no longer uses argument resolvers. Update any custom resolvers or middleware relying on this.
  • Event Arguments: Reworked event arguments may require updates to event listeners.

Debugging

  • Source Extraction Errors: Catch SourceExtractionException when data extraction fails:
    try {
        $dto = new CreateUserDto($request->get('data'));
    } catch (SourceExtractionException $e) {
        abort(400, 'Invalid request data structure');
    }
    
  • Validation Errors: Use dd($request->get('dto_validation_errors')) to inspect stored violations.

Performance Tips

  • Lazy Validation: Disable validation for non-critical paths using options: ['validate' => false].
  • Caching: Cache DTO validation metadata if using complex constraints.

Extension Points

  • Custom Validators: Implement Vendor\Package\Contract\ValidatorInterface for non-Symfony validation.
  • Event Subscribers: Subscribe to PostDtoValidationEvent for post-processing:
    public static function getSubscribedEvents()
    {
        return [
            PostDtoValidationEvent::class => 'onDtoValidated',
        ];
    }
    

Configuration Quirks

  • Symfony Validator Suggestion: The package suggests symfony/validator but remains compatible with Laravel’s validator. Ensure constraints are compatible with your chosen validator.
  • Attribute Autoloading: Enable PHP 8 attributes in composer.json:
    "autoload": {
        "psr-4": { "App\\": "app/" },
        "files": ["vendor/vendor/package/src/Attribute/Dto.php"]
    }
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime