spatie/data-transfer-object
PHP 8+ data transfer objects with “batteries included”: map and cast input arrays into typed DTOs, validate via attributes, and handle nested objects/collections. Note: package is deprecated; consider spatie/laravel-data or cuyz/valinor.
Begin by installing the package:
composer require spatie/data-transfer-object
Create a basic DTO by extending Spatie\DataTransferObject\DataTransferObject. Start with simple scalar properties, then gradually introduce nested DTOs, collections, and casters. The package uses PHP 8+ attributes (#[...]) for configuration, so ensure your environment supports attributes. The core use case is converting raw arrays (e.g., API responses, database results) into strongly-typed objects — ideal for API payloads or service layer communication. The simplest entry point is using named arguments to instantiate a DTO, leveraging PHP’s named parameter syntax for clarity.
#[CastWith(...)] to specify custom caster logic.Spatie\DataTransferObject\Caster to transform non-standard types (e.g., enums, value objects,DateTimeImmutable). Use DefaultCast attributes on abstract base DTOs to apply casters globally for certain types.#[MapFrom('source.key')] to rename or destructure input data (including dot-notation paths like user.address.city). Combine with #[MapTo(...)] when serializing back to arrays (e.g., for API responses or storage).Spatie\DataTransferObject\Validator to validate values during construction — similar to how #[NumberBetween(...)] is used in the README. This keeps validation declarative and close to property definitions.clone() method to create modified copies without mutating the original. Avoid direct property mutation to maintain safety across threads or middleware.only(), except(), and toArray() for controlled serialization. Prefer toArray() over all() for nested DTO-to-array conversion.spatie/laravel-data (if using Laravel) or cuyz/valinor (PSR-7/17-aligned, modern PHP). Continuing to use this package increases long-term maintenance risk.#[Strict] to enforce explicit property declarations — essential for catching typos or schema mismatches in APIs.^8.0). v2 exists for PHP 7 but lacks modern features (attributes, union types).DataTransferObjectCollection. Implement custom collections or use Laravel’s Collection with a tailored ArrayCaster for type-safe iteration and operations.#[CastWith(..., arg: value)]. Verify this order when debugging cast failures.ValidationResult but do not stop execution by default. You must check $dto->isValid() or inspect $dto->getValidationErrors() manually if using validators.#[MapFrom] edge cases to validate flexible deserialization.How can I help you explore Laravel packages today?