Download the PHP package eventsauce/object-hydrator without Composer
On this page you can find all versions of the php package eventsauce/object-hydrator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download eventsauce/object-hydrator
More information about eventsauce/object-hydrator
Files in eventsauce/object-hydrator
Package object-hydrator
Short Description Converts structured data into strict objects.
License MIT
Informations about the package object-hydrator
Object Hydrator (and Serializer)
Installation
Skip to usage documentation.
About
This library allows magic-less conversion from serialized data to object and back. Unlike other object mappers, this library does not rely on magic reflection to set private properties. It hydrates and serializes objects as if you would do it by hand. The hydration mechanism inspects the constructor and figures out which keys need to map to which properties. The serialization mechanism inspects all public properties and getter-methods, converts the values from objects to plain data-structures. Unlike "magic" hydration mechanisms, that are able to grab private properties, this way to map objects opens the door to object mapping without reflection. You get all the convenience with none of the guilt (or performance hits).
This is a utility that converts structured request data (for example: decoded JSON) into a complex object structure. The intended use of this utility is to receive request data and convert this into Command or Query object. The library is designed to follow a convention and does not validate input.
When and why would you use this?
That's a good question, so let's dig in. Initially, this library was created to map plain data (like JSON request bodies) to strict object structures. The use of object (DTOs, Query and Command objects) is a great way to create expressive code that is easy to understand. Objects can be trusted to correctly represent concepts in your domain. The downside of using these objects is that they can be tedious to use. Construction and serialization becomes repetitive and writing the same code over and over is boring. This library aims to remove the boring parts of object hydration and serialization.
This library was built with two specific use-cases in mind:
- Construction of DTOs, Query-object, and Command-objects.
- Serialization and hydration of Event-objects.
Object hydration and serialization can be achieved at zero expense, due to an ahead-of-time resolving steps using code generation.
Quick links:
- Installation
- About
- Design goals
- Usage
- Custom mapping key
- Mapping from multiple keys
- Property casting
- Casting to scalar values
- Casting to a list of scalar values
- Casting to a list of objects
- Casting to DateTimeImmutable objects
- Casting to Uuid objects (ramsey/uuid)
- Using multiple casters per property
- Creating your own property casters
- Static constructors
- Key formatters
- Maximizing performance
Design goals
This package was created with a couple design goals in mind. They are the following:
- Object creation should not be too magical (use no reflection for instantiation)
- There should not be a hard runtime requirement on reflection
- Constructed objects should be valid from construction
- Construction through (static) named constructors should be supported
Usage
This library supports hydration and serialization of objects.
- Hydration Usage
- Serilization Usage
Hydration usage
By default, input is mapped by property name, and types need to match. By default, keys are mapped from snake_case input
to camelCase properties. If you want to keep the key names you can use the KeyFormatterWithoutConversion
.
Complex objects are automagically resolved.
A simple doc-comment ensures that arrays of objects are automagically converted.
The library supports the following formats:
@param Type[] $name
@param array<Type> $name
@param array<string, Type> $name
@param array<int, Type> $name
Custom mapping key
Mapping from multiple keys
You can pass an array to capture input from multiple input keys. This is useful when multiple values represent a singular code concept. The array allows you to rename keys as well, further decoupling the input from the constructed object graph.
Property casting
When the input type and property types are not compatible, values can be cast to specific scalar types.
Casting to scalar values
Casting to a list of scalar values
Casting to a list of objects
Casting to DateTimeImmutable objects
Casting to Uuid objects (ramsey/uuid)
Using multiple casters per property
Create rich compositions of casting by using multiple casters.
Creating your own property casters
You can create your own property caster to handle complex cases that cannot follow the default conventions. Common cases for casters are union types or intersection types.
Property casters give you full control over how a property is constructed. Property casters are attached to properties using attributes, in fact, they are attributes.
Let's look at an example of a property caster:
You can now use these as attributes on the object you wish to hydrate:
Static constructors
Objects that require construction through static construction are supported. Mark the static method using
the Constructor
attribute. In these cases, the attributes should be placed on the parameters of the
static constructor, not on __construct
.
Key formatters
By default, keys are converted from snake_case input to camelCase properties. However, you can
control how keys are mapped by passing a key formatter to the DefinitionProvider
that is handed to
the object mapper constructor:
This library ships with a KeyFormatterWithoutConversion
that can be used if no conversion is
desired. You can implement the
KeyFormatter
interface if you need custom conversion logic.
Serialization usage
By default, this library maps the public properties and getters to snake_cased
arrays with plain data.
When user-defined objects are encountered, these are automatically converted to the plain data counterpart.
Custom key mapping
Serialization inverts the key mapping used by hydration in a symmetrical way, including the mapping from multiple keys.
Property serialization
Similar to casters, custom serialization logic can be added by using "property serializers". Property serialization are custom annotations that provide a hook into the serialization process, allowing you to gain full control over the serialization mechanism whenever you need it.
Symmetrical conversion
If configured consistently, hydration and serialization can be used to translate an object to raw data
and back to the original object. A class can implement both the PropertyCasterand
PropertySerializer`
interface to become a symmetrical conversion mechanism.
An example of this is the implementation of CastToArrayWithKey
:
It's important to know that serialization and hydration hooks are triggered before any default conversion happens. If you wish to operate on serialized or hydrated data, you can hydrate/serialize the inner data/objects.
⚠️ Caster and serializer order
In order to make hydration and serialization symmetrical (allowing back and forth conversion), the order of serializers called is reversed for promoted properties.
Omitting data for serialization
Data can be omitted from serialization. By default, all public methods and properties are included for serialization. There are two ways to exclude data, both methods use attributes.
The MapperSettings
attribute can be specified at class-level to exclude either all
public properties, public methods, or both (the last being rather useless, of course).
The MapperSettings
attribute can also be specified on interfaces that are implemented
by classes. In this case, the first available MapperSettings
will be used.
⚠️ Note that MapperSettings
defined on parent classes will not be used,
to prevent confusion and ensure consistent performance with class inheritance.
Alternatively, specific methods and properties can be excluded from serialization by
using the DoNotSerialize
attribute.
Maximizing performance
Reflection and dynamic code paths can be a performance issue in the hot-path. To remove the expense, an optimized implementation can be generated. The generated PHP code performs the same hydration and serialization of classes as the reflection-based implementation would. It's sort of a pre-compiler for this logic.
You can generate a fully optimized mapper for a known set of classes. The generator will produce the code required for constructing the entire object tree, automatically resolving the nested proprties it must map.
The dumped code is 3-10x faster than the reflection based implementation.
Tip: Use league/construct-finder
You can use the construct finder package from The PHP League to find all classes in a given directory.
Alternatives
This package is not unique, there are a couple implementations our there that do the same, similar, or more than this package does.
All versions of object-hydrator with dependencies
ext-fileinfo Version *