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

Dart Dto Bundle Laravel Package

dayploy/dart-dto-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package to your Laravel project via Composer:

    composer require dayploy/dart-dto-bundle
    

    Publish the bundle configuration (if applicable):

    php artisan vendor:publish --provider="Dayploy\DartDtoBundle\DartDtoServiceProvider"
    
  2. First Use Case: Basic DTO Definition Define a simple Data Transfer Object (DTO) in a dedicated Dto namespace (e.g., App\Dto):

    namespace App\Dto;
    
    use Dayploy\DartDtoBundle\Dto\Dto;
    
    class UserDto extends Dto
    {
        public string $name;
        public int $age;
    }
    
  3. Instantiation & Usage Instantiate and populate the DTO:

    $userDto = new UserDto();
    $userDto->name = 'John Doe';
    $userDto->age = 30;
    
    // Convert to array (if needed)
    $array = $userDto->toArray();
    
  4. Key Files to Review

    • config/dart-dto.php (if published)
    • src/Dto/Dto.php (base class)
    • src/Traits/ (optional traits for validation, casting, etc.)

Implementation Patterns

1. DTO as API Request/Response Wrapper

Workflow:

  • Use DTOs to structure incoming API requests (e.g., via Illuminate\Http\Request).
  • Example: Validate and map request data to a DTO:
    use Dayploy\DartDtoBundle\Dto\Dto;
    use Illuminate\Http\Request;
    
    class StoreUserRequestDto extends Dto
    {
        public string $name;
        public string $email;
    
        public function rules(): array
        {
            return [
                'name'  => 'required|string|max:255',
                'email' => 'required|email',
            ];
        }
    }
    
    // In a controller:
    $dto = new StoreUserRequestDto();
    $dto->fill(request()->all());
    $dto->validate(); // Built-in validation
    

2. DTO for Eloquent Model Mapping

Pattern:

  • Convert Eloquent models to DTOs for consistent API responses.
  • Example:
    use App\Models\User;
    use App\Dto\UserDto;
    
    $user = User::find(1);
    $dto = UserDto::fromModel($user); // Hypothetical static method
    return response()->json($dto->toArray());
    

3. Nested DTOs

Integration Tip:

  • Support hierarchical data by nesting DTOs:
    class AddressDto extends Dto
    {
        public string $street;
        public string $city;
    }
    
    class UserDto extends Dto
    {
        public string $name;
        public AddressDto $address;
    }
    
  • Use JsonSerializable or custom toArray() methods to flatten nested structures.

4. DTO in Form Requests

Workflow:

  • Extend Laravel’s FormRequest to work with DTOs:
    use Illuminate\Foundation\Http\FormRequest;
    use App\Dto\StoreUserRequestDto;
    
    class StoreUserRequest extends FormRequest
    {
        public function validateDto(): StoreUserRequestDto
        {
            $dto = new StoreUserRequestDto();
            $dto->fill($this->validated());
            $dto->validate();
            return $dto;
        }
    }
    

5. DTO for Command Bus (Laravel Echo)

Pattern:

  • Use DTOs as payloads for command/handler patterns:
    use Dayploy\DartDtoBundle\Dto\Dto;
    use Illuminate\Support\Facades\Bus;
    
    class SendEmailCommandDto extends Dto
    {
        public string $to;
        public string $subject;
        public string $body;
    }
    
    Bus::dispatch(new SendEmailCommand($dto));
    

Gotchas and Tips

Pitfalls

  1. Missing Base Class Methods

    • The base Dto class may lack common methods like toArray(), fromArray(), or validate(). Override these explicitly:
      public function toArray(): array
      {
          return (array) $this;
      }
      
  2. No Built-in Validation

    • Unlike packages like spatie/laravel-data, this bundle doesn’t include validation rules by default. Implement manually or extend the base class:
      use Illuminate\Support\Facades\Validator;
      
      public function validate(): void
      {
          $validator = Validator::make((array) $this, $this->rules());
          if ($validator->fails()) {
              throw new \InvalidArgumentException($validator->errors()->first());
          }
      }
      
  3. Circular References in Nested DTOs

    • Nested DTOs with circular references (e.g., UserDto containing PostDto which references UserDto) will cause infinite loops in toArray(). Use JsonSerializable or custom serialization logic:
      public function jsonSerialize(): array
      {
          return [
              'name' => $this->name,
              'address' => $this->address?->jsonSerialize(), // Safe call
          ];
      }
      
  4. Type Safety

    • PHP’s dynamic nature means type hints in DTOs are advisory. Use runtime checks:
      public function setAge(int $age): void
      {
          if (!is_int($age)) {
              throw new \InvalidArgumentException('Age must be an integer.');
          }
          $this->age = $age;
      }
      

Debugging Tips

  1. Enable Strict Typing Add to composer.json to catch type-related issues early:

    "config": {
        "preferred-visibility": "private",
        "sort-packages": true,
        "platform-check": true
    }
    
  2. Log DTO Instantiation Override __construct() to log DTO creation (useful for debugging):

    public function __construct()
    {
        \Log::debug("DTO {$this::class} instantiated");
    }
    
  3. Use get_object_vars() for Debugging Quickly inspect DTO properties:

    dd(get_object_vars($dto));
    

Extension Points

  1. Add Custom Traits Extend functionality with traits (e.g., for API resource conversion):

    use Dayploy\DartDtoBundle\Dto\Dto;
    
    trait ApiResourceable
    {
        public function toApiResource(): array
        {
            return array_filter((array) $this, fn ($value) => $value !== null, ARRAY_FILTER_USE_BOTH);
        }
    }
    
    class UserDto extends Dto
    {
        use ApiResourceable;
    }
    
  2. Integrate with Laravel Scout Use DTOs to standardize searchable attributes:

    class SearchableDto extends Dto
    {
        public function toSearchableArray(): array
        {
            return [
                'name' => $this->name,
                'tags' => explode(',', $this->tags),
            ];
        }
    }
    
  3. DTO Factory Create a factory class to instantiate DTOs from various sources (e.g., database, API):

    class DtoFactory
    {
        public static function fromModel(User $user): UserDto
        {
            return (new UserDto())
                ->setName($user->name)
                ->setEmail($user->email);
        }
    }
    

Configuration Quirks

  • No Default Config File The package may not publish a config file by default. Check if config/dart-dto.php exists or create it manually to define global DTO behaviors (e.g., default validation rules).

  • Namespace Collisions Ensure your Dto classes are in a unique namespace (e.g., App\Dto) to avoid conflicts with Laravel’s built-in classes or other packages.

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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle