webgraphe / phlux
Yet another PHP DataTransferObject library
Installs: 3
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/webgraphe/phlux
Requires
- php: ^8.4
Requires (Dev)
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^12.0
- psy/psysh: ^0.12.7
README
A DTO (Data Transfer Object) is a simple object holding data to be moved between different subsystems or layers of an application. They typically only contain public fields, constructors and getters. Therefore, a DTO:
- MUST be easy to understand
- MUST present and allow data transport in the simplest way
- SHOULD not contain business logic
- SHOULD be immutable, i.e. its state should not change after it is created
This is Phlux.
Declaration
A Phlux DTO is strictly declared using PHP language constructs; there is no magic.
The bare minimum to make a class into a DTO is to extend the readonly class Data which implements
DataTransferObject, inheriting JsonSerializable and IteratorAggregate in the process.
Important
While not guaranteed to be immutable, a readonly class ensures instances cannot be tampered with after
initialization, albeit with some caveats:
- A DTO cannot have
staticproperties - All properties MUST be typed
- It's still possible to initialize an uninitialized property after construction (albeit in a
protected(set)manner)
Supported property types range from:
- Scalars (
int,float,string,bool) - Composites (
array,object) null- Anything extending
Data DateTimeInterface,DateTimeImmutableandBackedEnum
array properties are always hydrated as 0-based lists. object properties are always hydrated as a key-value map
instances of stdClass. Without attributes, composites can store arbitrary data.
A composite property may narrow the type(s) of items it contains with the #[ItemType] attribute, passing a
class-string or the name of any aforementioned supported types above.
An #[ItemPrototype] attribute may be declared with the name of another property of the same class to be used as
the prototype of the collection's item (non-public properties can used as prototype for that effect).
All properties can be nullable by either prefixing the type name with a question mark or declaring a union with null.
When the data for a property is missing from a payload, unless a #[Present] attribute
is found on the property (indicating to skip initialization), a default value is assigned:
nullwhen nullable0forint0.0forfloatfalseforbool''forstring[]forarraynew stdClass()forobject- Current time for anything implementing
DateTimeInterfaceand anything extendingDateTimeImmutable - The first
BackedEnum::cases()item forenum - A new instance with
nullpayload for anything implementingDataTransferObject
Note
Uninitialized properties are not serialized.
Adding the #[Discriminator] attribute on a DataTransferObject class (MUST be abstract)
allows for inheritance and polymorphism of DTOs and their properties to hydrate. It must be given the name of a
final, non-nullable string property on the attributed class containing the discriminator value which can be matched
against a given mapping or composed with the namespace of the discriminated DTO.
There is no support (yet) for Union or Intersection properties, except unions with null.
Presentation and transportation are handled for all public properties (non-public properties may be defined but are
not serialized).
Instantiation
DTOs may be hydrated in different ways:
The static method instantiate() acts as a constructor by accepting parameters named after its public properties. For
discriminated DTOs, it resolves the discriminator value automatically.
The static method from() is suitable for unmarshalling payloads, such as decoded JSON, stdClass, ArrayObject
or SPL data structures (that can be transformed into raw PHP composites).
Methods lazyInstantiate() and lazyFrom() creates lazy instances that initializes only when observed, which may
reduce the number of previous CPU cycles when dealing with big nested DTOs and complex business logic partially
navigating them.
Caution
Lazy DTO instantiations will defer exceptions that would otherwise have been thrown at creation time with their non-lazy corresponding methods only when they are observed for the first time; it is advised to unit test your work without lazy instances to validate your Data Transfer Object definitions.
<?php readonly class Person extends Webgraphe\Phlux\Data { public function __construct( public string $firstName, #[Present] public string $lastName, ); } // in-lieu of the constructor, creating with instantiate() (notice lastName is missing) $johnDoe = Person::instantiate(firstName: 'John'); var_dump(isset($johnDoe->lastName)); // false, #Present attribute prevented initialization with default value '' // Creating from an existing DTO $johnDoeClone = Person::from($johnDoe); // Encoding to JSON $json = json_encode($johnDoe); // Creating from decoded JSON $johnDoeDeepClone = Person::from(json_decode($johnDoe)); // Creating as lazy-object, hydrated from an associative array $lazyJohnDoe = Person::lazyFrom(json_decode($json, true)); var_dump(Webgraphe\Phlux\Data::isLazy($lazyJohnDoe)); // true // Lazy object initializes its properties ONLY when observed echo $lazyJohnDoe->firstName; // prints "John" var_dump(Webgraphe\Phlux\Data::isLazy($lazyJohnDoe)); // false; it's now initialized