Download the PHP package om/from-array without Composer
On this page you can find all versions of the php package om/from-array. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download om/from-array
More information about om/from-array
Files in om/from-array
Package from-array
Short Description fromArray trait allow create objects instances loaded with initial data array
License BSD-3-Clause
Informations about the package from-array
FromArray
Data Loader Trait
Introduction
FromArray
is a lightweight PHP trait that enables effortless object hydration from associative arrays. It is
especially useful in scenarios where data needs to be mapped into strongly-typed objects, such as when working with
APIs, form inputs, or configuration data.
With support for PHP attributes, FromArray
lets you fine-tune how each property is loaded, define type expectations,
and apply custom transformation logic—all while keeping your code clean and expressive.
Install
Usage
The fromArray
trait enables the creation of object instances preloaded with an initial data array:
And that will be the result:
The trait works with public properties only – private and protected properties will be ignored.
The Property
, Loader
and Type
attributes
There are few PHP Attributes to
configure the fromArray
behavior:
Property
The Property
attribute allows you to define a specific key (from
) from the data array that will be mapped to the
property.
You can also customize the loader
used to load the data:
Loader can also be the name of a class, an object, or any type of callable function.
For more see basic-example.php.
Loader
The Loader
attribute allows you to define a specific value loader for the property. You can add global loaders to the
class or to the property.
For more see loader-property.php-
Type
The Type
attribute allows you to define a specific type for the property. Types are usually auto detected, but you can
force the type using the Type
attribute.
There is one special case for the Type
, you can specify Types::ArrayOfObjects
type to load an array of objects with
the same class. The class
parameter is required in this case.
See array-of-objects.php for more information.
Metadata
There is a Metadata
object, that contains all the
information about the class and its properties. Metadata
object is singleton, but you can load instance from any type
of cache.
See metadata-cache.php for more information.
Testing
How to run the tests: