arens-myzyri/data-transformation-and-serialization
Installation:
composer require arens-myzyri/data-transformation-and-serializer
Ensure your project meets the requirements (PHP 8.1+, Symfony 6.2+).
First Use Case:
Inject the DataTransformerInterface into a service/controller:
use ArensMyzyri\DataTransformationAndSerializer\DataTransformerInterface;
public function __construct(private DataTransformerInterface $transformer) {}
// Transform a model to JSON
$json = $this->transformer->transformModelToJson($model);
Key Methods:
transformModelToJson($model) → Serializes a model to JSON.transformJsonToModel($json, Model::class) → Deserializes JSON to a model.transformArrayToModel($array, Model::class) → Converts an array to a model.Where to Look First:
Model Serialization:
Use transformModelToJson() for API responses or caching:
$response = $this->transformer->transformModelToJson($user);
return response()->json($response);
Deserialization: Convert JSON/API payloads to Eloquent models:
$userData = json_decode(request()->getContent(), true);
$user = $this->transformer->transformJsonToModel($userData, User::class);
Array-to-Model Conversion: Transform form submissions or legacy data:
$formData = request()->all();
$model = $this->transformer->transformArrayToModel($formData, Post::class);
Symfony Serializer Compatibility:
Leverage Symfony’s built-in normalization groups (e.g., @Groups({"api"})) for granular control over serialization.
Custom Transformers:
Extend the package by implementing DataTransformerInterface or using Symfony’s Normalizer/Denormalizer interfaces.
Validation:
Combine with Laravel’s Validator or Symfony’s Validator to sanitize data before/after transformation:
$data = $this->transformer->transformJsonToModel($json, User::class);
$validator = Validator::make($data->toArray(), User::$rules);
Caching Responses: Cache serialized JSON responses for performance:
$cacheKey = 'user:'.$user->id;
$json = Cache::remember($cacheKey, 3600, fn() =>
$this->transformer->transformModelToJson($user)
);
API Resource Integration:
Use alongside Laravel’s JsonResource for hybrid serialization:
$resource = new UserResource($user);
$json = $this->transformer->transformModelToJson($resource);
Symfony Dependency Conflicts:
Serializer). If your project uses Laravel without Symfony, ensure compatibility or mock dependencies during testing.symfony/runtime to isolate Symfony dependencies if needed.Circular References:
User->posts->author->user).@MaxDepth or @Ignore attributes:
#[Ignore]
public function getPosts() { ... }
Type Mismatches:
transformJsonToModel() assumes JSON keys match model properties exactly. Nested objects/arrays may fail silently.transformArrayToModel() for more control or implement a custom denormalizer.Performance Overhead:
Laravel-Specific Quirks:
->toArray() or ->jsonSerialize() to normalize data before transformation.Enable Symfony Debug: Configure Symfony’s serializer debug mode to inspect normalization:
# config/packages/serializer.yaml
framework:
serializer:
debug: true
Log Normalization Groups: Add debug logs to track which groups are applied:
$this->transformer->transformModelToJson($model, ['groups' => ['api', 'debug']]);
Custom Normalizers/Denormalizers: Register Symfony’s normalizers for custom types (e.g., Carbon instances):
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
$normalizers = [
new DateTimeNormalizer(),
// ...
];
$this->transformer->setNormalizers($normalizers);
Event Listeners:
Hook into Symfony’s serialize/deserialize events for pre/post-processing:
$serializer->addSubscriber(new class implements SerializerSubscriberInterface {
public function hasEvents(): bool { return true; }
public function getSubscribedEvents(): array {
return [
Serializer::EVENT_SERIALIZE => 'onSerialize',
Serializer::EVENT_DESERIALIZE => 'onDeserialize',
];
}
});
Configuration Overrides: Override default serializer settings via dependency injection:
$serializer = Serializer::create([
'json' => ['ignore_unknown_fields' => false],
]);
$this->transformer->setSerializer($serializer);
Use for API Versioning: Leverage normalization groups to version API responses without breaking changes:
// v1
$json = $this->transformer->transformModelToJson($user, ['groups' => ['v1']]);
// v2
$json = $this->transformer->transformModelToJson($user, ['groups' => ['v2']]);
Batch Processing: Transform collections efficiently:
$users = User::all();
$json = $this->transformer->transformModelToJson($users); // Handles collections
Testing:
Mock DataTransformerInterface in unit tests to isolate serialization logic:
$this->mock(DataTransformerInterface::class)->shouldReceive('transformModelToJson')
->once()->andReturn('{"id":1}');
How can I help you explore Laravel packages today?