This PHP Data Model package provides a lightweight, non-invasive way to hydrate type-safe PHP objects recursively. It uses reflection and PHP attributes to hydrate objects and instantiate them based on type hints:
class Address
{
use \Zerotoprod\DataModel\DataModel;
public string $street;
public string $city;
}
class User
{
use \Zerotoprod\DataModel\DataModel;
public string $username;
public Address $address;
}
$User = User::from([
'username' => 'John Doe',
'address' => [
'street' => '123 Main St',
'city' => 'Hometown',
],
]);
echo $User->address->city; // Hometown
Main Features
- Simplify Object Hydration: No more manual assignment of properties or repetitive boilerplate code. A DataModel automates the process, ensuring your objects are populated correctly based on their type declarations.
- Ensure Type Safety: Type safety is enforced by PHP itself. With a DataModel, you can trust that your objects contain the expected types without extra validation.
- Reduce Defensive Programming: Instead of writing defensive code to check and sanitize your data, a DataModel allows you to define how each property should be resolved before the object is hydrated.
- Flexible Value Resolution: With the #[Describe()] attribute, you control how values are resolved for each property, including transformations, default values, and custom casting. This ensures that your data model behaves exactly as you intend.
- Non-Invasive Integration: Simply add the DataModel trait to your classes. There’s no need to extend base classes or implement interfaces, keeping your class hierarchy clean.
This package also includes advanced features like required properties that are enforced via a PHP attribute:
use Zerotoprod\DataModel\Describe;
class User
{
use \Zerotoprod\DataModel\DataModel;
#[Describe(['required' => true])]
public string $username;
public string $email;
}
User::from(['email' => 'john@example.com']);
// Throws PropertyRequiredException exception:
// Property: username is required
Additional related packages also provide helpers, factories, transformers, and more. You can get started with this package by reading the documentation; the source code is also available on GitHub at zero-to-prod/data-model.
The post Transform Data into Type-safe DTOs with this PHP Package appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.