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)
You can install the package via composer:
composer require brendt/php-make-object
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);
$post = make(Post::class)->from([
'title' => 'test',
]);
$post = make(Post::class)->from(<<<JSON
{
"title": "test"
}
JSON);
$post = make(Post::class)->from(<<<XML
<post>
<title>test</title>
</post>
XML);
$post = make(Post::class)->from(__DIR__ . '/post.json');
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',
];
}
}
$posts = make(Post::class)->fromCollection([
['title' => 'a'],
['title' => 'b'],
['title' => 'c'],
]);
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.