create-dto
Generates a Data Transfer Object (DTO) class. Use when defining structured data for Contracts, API responses, or complex Action inputs.
When & Why to Use This Skill
This Claude skill automates the generation of PHP Data Transfer Objects (DTOs) to ensure type safety and structural consistency across application layers. It leverages modern PHP 8.2+ features like readonly classes and static factories to streamline data handling for APIs, contracts, and internal module communication, significantly reducing boilerplate code and manual errors.
Use Cases
- Standardizing API responses by defining structured DTOs that ensure consistent data delivery to client applications and external consumers.
- Enforcing type safety in complex business logic by using DTOs as validated inputs for Actions and Services within modular architectures.
- Facilitating seamless data mapping from HTTP requests or raw arrays into immutable objects using built-in static factory methods like fromArray.
- Improving code maintainability and IDE autocompletion by replacing loosely typed associative arrays with strictly typed, readonly DTO classes.
- Defining clear data contracts between different microservices or modules to prevent integration errors and simplify debugging.
| name | create-dto |
|---|---|
| description | Generates a Data Transfer Object (DTO) class. Use when defining structured data for Contracts, API responses, or complex Action inputs. |
| allowed-tools | Write, Read |
Create DTO
This skill generates a Data Transfer Object (DTO) to ensure type safety for data moving between Modules or Layers.
Instructions
Identify Parameters:
- Module: (e.g.,
Identity,Academic) orSharedif used across modules. - Purpose: What data does it hold? (e.g.,
StudentRegistrationData,CourseSummary). - Path:
app/Modules/{Module}/DTO/{ClassName}.phporapp/Shared/DTO/{ClassName}.php.
- Module: (e.g.,
Generate Code:
- Namespace:
App\Modules\{Module}\DTOorApp\Shared\DTO. - Use
readonlyclass (PHP 8.2+). - Public typed properties.
- Optional:
fromRequestorfromArraystatic factories.
- Namespace:
Template
<?php
namespace App\Shared\DTO;
use Illuminate\Http\Request;
readonly class StudentGpaDTO
{
public function __construct(
public int $studentId,
public string $studentName,
public float $gpa,
public int $totalCredits,
public ?string $rank = null,
) {}
public static function fromArray(array $data): self
{
return new self(
studentId: $data['student_id'],
studentName: $data['student_name'],
gpa: (float) $data['gpa'],
totalCredits: (int) $data['total_credits'],
rank: $data['rank'] ?? null,
);
}
}
Best Practices
- Immutability: Always use
readonlyclasses. - Strict Typing: All properties must have types.
- Shared vs Module: If it's the return type of a
Shared Contract, put it inapp/Shared/DTO. If it's internal to a module (e.g. Action input), put it inapp/Modules/{Module}/DTO.