Serializer class for extracting data from objects annotated with the #[Serialize] attribute.
This class provides a method, serialize, to transform an object into an associative array by extracting data from its properties and constants based on the #[Serialize] attribute.
composer require phauthentic/attribute-serializerAdd the #[Serialize()] attribute to the property or constant. You can rename the property in the resulting array by providing a name to the attribute #[Serialize('other-name')].
class Example {
#[Serialize('username')]
private $name = 'serializer';
}
var_dump((new Serializer())->serialize(new Example()));[
'username' => 'serializer'
]
Field names can be dynamically renamed, even into deeper array structures, by using the dot notation.
class Example2 {
#[Serialize('first.second')]
private $name = 'serializer';
}
var_dump((new Serializer())->serialize(new Example2());[
'first' => [
'second' => 'serializer'
]
]
class Example3 {
use ToArrayTrait;
#[Serialize('username')]
private $name = 'serializer';
}
var_dump((new Example3)->toArray());[
'username' => 'serializer'
]
Copyright Florian Krämer
Licensed under the MIT license.