brendt / php-make-object
Simple wrapper for symfony/serializer for the 90% use-case
Fund package maintenance!
brendt
Requires
- php: ^8.1
- illuminate/collections: ^9.42
- phpdocumentor/reflection-docblock: ^5.3
- symfony/property-access: ^6.0
- symfony/serializer: ^6.0
- symfony/validator: ^6.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- larapack/dd: ^1.1
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-12-09 17:02:25 UTC
README
Write this:
$post = make(Post::class)->from($postData);
instead of this:
$reflectionExtractor = new ReflectionExtractor(); $phpDocExtractor = new PhpDocExtractor(); $propertyTypeExtractor = new PropertyInfoExtractor( listExtractors: [$reflectionExtractor], typeExtractors: [$phpDocExtractor, $reflectionExtractor], descriptionExtractors: [$phpDocExtractor], accessExtractors: [$reflectionExtractor], initializableExtractors: [$reflectionExtractor] ); $normalizer = new ObjectNormalizer( propertyTypeExtractor: $propertyTypeExtractor ); $arrayNormalizer = new ArrayDenormalizer(); $serializer = new SymfonySerializer( normalizers: [ $arrayNormalizer, $normalizer, ], encoders: [ new XmlEncoder(), new JsonEncoder(), ], ); $post = $serializer->denormalize($postData, Post::class)
Installation
You can install the package via composer:
composer require brendt/php-make-object
Usage
This package abstracts away all configuration needed for complex deserialization with symfony/serializer. All you need to do is say which class you want to make, provide it some input (arrays, JSON, XML, files or objects), and this package will take care of the rest.
Added bonus: proper static analysis, so you'll know what kind of object was created.
$post = make(Post::class)->from($postData);
Input types
Arrays
$post = make(Post::class)->from([ 'title' => 'test', ]);
JSON
$post = make(Post::class)->from(<<<JSON { "title": "test" } JSON);
XML
$post = make(Post::class)->from(<<<XML <post> <title>test</title> </post> XML);
Files
$post = make(Post::class)->from(__DIR__ . '/post.json');
The Make
interface
The Make
interface can be added on any class, allowing that class to provide data that can be used to create an object.
$post = make(Post::class)->from(new PostRequest());
final class PostRequest implements Makes { public function data(): array { return [ 'title' => 'test', ]; } }
Collections
$posts = make(Post::class)->fromCollection([ ['title' => 'a'], ['title' => 'b'], ['title' => 'c'], ]);
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Credits
License
The MIT License (MIT). Please see License File for more information.