Simple and lightweight PHP library for representing Data Transfer Objects (DTOs) with property value tracking.
- Easy to use abstract
Dtoclass for creating data transfer objects - Property value tracking with
Propertywrapper class - Support for creating DTOs from arrays with automatic property name conversion
- Track whether properties are initialized or not
- Automatic conversion between kebab-case and camelCase
- Type-safe with PHP 7.4+ and PHP 8.0+
Install the library via Composer:
composer require diffhead/php-dtoRun the test suite:
composer test- PHP 7.4 or higher
diffhead/php-interfaces^1.0jawira/case-converter^3.6
Create a DTO class by extending the Dto abstract class:
<?php
use Diffhead\PHP\Dto\Dto;
use Diffhead\PHP\Dto\Property;
/**
* Properties inside the Dto class
* should be camelCase named and
* protected
*/
class UserCreate extends Dto
{
protected Property $firstName;
protected Property $lastName;
protected Property $email;
}/**
* But inside the source array you can use
* camelCase, pascal_case, kebab-case, etc
*/
$data = [
'first_name' => 'John',
'lastName' => 'Doe',
'email' => 'john@example.com'
];
$user = UserCreate::fromArray($data);Access properties using magic methods.
Each property returns a Property object that
tracks both the value and whether it exists:
/**
* Get the property object
*/
$firstName = $user->firstName;
/**
* Check property exists and set
*/
if ($firstName->exists()) {
echo $firstName->value(); // Output: John
}The Property class wraps values and tracks their existence:
$property = new \Diffhead\PHP\Dto\Property('1', true);
$property->value(); // Returns: '1'
$property->exists(); // Returns: true
$property->toInt(); // Returns: 1
$property->toFloat(); // Returns: 1.0
$proprety->toBool(); // Returns: true
$property->toArray(); // Returns: ['1']
$property->toString(); // Returns: '1'
$property = new \Diffhead\PHP\Dto\Property(null, false);
$property->value(); // Returns: null
$property->exists(); // Returns: falseGet multiple property values at once:
/**
* Get all properties values
*
* output: ['first_name' => 'John', 'lastName' => 'Doe', 'email' => 'john@example.com', 'age' => null]
*/
$values = $user->getValues(['first_name', 'lastName', 'email', 'age']);
/**
* Get only existing properties values
*
* output: ['first-name' => 'John', 'last.name' => 'Doe', 'email' => 'john@example.com']
*/
$values = $user->getValues(['first-name', 'last.name', 'email', 'age'], true);The library automatically handles class property name conversion:
- dot.case (e.g.,
first.name) → camelCase (e.g.,firstName) - kebab-case (e.g.,
first-name) → camelCase (e.g.,firstName) - snake_case (e.g.,
first_name) → camelCase (e.g.,firstName)
This makes it easy to work with API responses and form data that might use different naming conventions.
But Diffhead\PHP\Dto\Dto::getValues method
returns raw array keys as they was been passed.
This project is licensed under the MIT License. See the LICENSE file for details.