https://github.com/phauthentic/attribute-serializer
A serializer to transform an object into an associative array by extracting data from its properties and constants based on the #[Serialize] attribute.
https://github.com/phauthentic/attribute-serializer
attributes php8 serialization serializer solid-principles
Last synced: about 1 year ago
JSON representation
A serializer to transform an object into an associative array by extracting data from its properties and constants based on the #[Serialize] attribute.
- Host: GitHub
- URL: https://github.com/phauthentic/attribute-serializer
- Owner: Phauthentic
- License: mit
- Created: 2024-02-25T12:24:18.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2024-02-25T16:49:07.000Z (over 2 years ago)
- Last Synced: 2025-03-29T07:43:00.728Z (about 1 year ago)
- Topics: attributes, php8, serialization, serializer, solid-principles
- Language: PHP
- Homepage:
- Size: 12.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Attribute Based Serializer



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.
## Installation
```sh
composer require phauthentic/attribute-serializer
```
## How to use it?
Add 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')]`.
```php
class Example {
#[Serialize('username')]
private $name = 'serializer';
}
var_dump((new Serializer())->serialize(new Example()));
```
```text
[
'username' => 'serializer'
]
```
### Dot notation for deep arrays
Field names can be dynamically renamed, even into deeper array structures, by using the dot notation.
```php
class Example2 {
#[Serialize('first.second')]
private $name = 'serializer';
}
var_dump((new Serializer())->serialize(new Example2());
```
```text
[
'first' => [
'second' => 'serializer'
]
]
```
### ToArrayTrait
```php
class Example3 {
use ToArrayTrait;
#[Serialize('username')]
private $name = 'serializer';
}
var_dump((new Example3)->toArray());
```
```text
[
'username' => 'serializer'
]
```
## License
Copyright Florian Krämer
Licensed under the [MIT license](LICENSE).