lastdragon-ru/lara-asp-serializer
Installation:
composer require lastdragon-ru/lara-asp-serializer
The package auto-registers, so no additional service provider configuration is needed.
First Use Case: Serialize a model or array to JSON with custom normalization:
use LastDragon\LaraAspSerializer\Facades\Serializer;
$data = User::find(1);
$serialized = Serializer::serialize($data, 'json');
Where to Look First:
LastDragon\LaraAspSerializer\Facades\Serializer (primary entry point).config/lara-asp-serializer.php (default settings, normalization groups, and encoders).Examples/ directory in the repo for use cases like nested objects, custom normalization, and API responses.Basic Serialization/Deserialization:
// Serialize to JSON
$json = Serializer::serialize($object, 'json');
// Deserialize from JSON
$object = Serializer::deserialize($json, get_class($object), 'json');
Normalization Groups:
Define groups in config (normalization_groups) and use them to control what gets serialized:
// In config/lara-asp-serializer.php
'normalization_groups' => [
'user:public' => ['id', 'name', 'email'],
'user:admin' => ['*'],
];
// Usage
$serialized = Serializer::serialize($user, 'json', ['groups' => ['user:public']]);
Custom Normalizers: Register a custom normalizer for a specific class:
Serializer::getContainer()->get('serializer')->getNormalizers()->addNormalizer(
new CallbackNormalizer(
fn ($object) => ['custom_key' => $object->customMethod()],
['groups' => ['user:custom']]
),
100 // Priority
);
API Responses: Integrate with Laravel responses for consistent JSON formatting:
return response()->json(
Serializer::serialize($data, 'json', ['groups' => ['api']])
);
Caching Serialized Data: Leverage Symfony’s cache system for performance:
$serialized = Serializer::serialize($data, 'json', [
'cache_key' => 'user.1.api',
'cache_ttl' => 3600,
]);
class User extends Model
{
public function getApiRepresentation(): array
{
return Serializer::normalize($this, ['groups' => ['user:public']]);
}
}
$validated = Serializer::deserialize(
$request->getContent(),
UserRequest::class,
'json'
);
$job = new ProcessUser($user->id);
$job->handle(Serializer::serialize($user, 'json'));
Circular References:
Symfony’s serializer handles circular references by default, but custom normalizers may break this. Use DenormalizerInterface or NormalizerInterface with ignore_circular_references: true in config.
Group Conflicts: If multiple normalization groups are defined for the same class, ensure priorities align with your use case. Overlapping groups may serialize unexpected data.
Performance with Large Data: Avoid serializing/deserializing massive datasets in loops. Use batch processing or caching:
// Bad: Serializing 10,000 records in a loop
foreach ($users as $user) {
$serialized = Serializer::serialize($user, 'json');
}
// Good: Batch and cache
$serializedBatch = Serializer::serialize($users, 'json', ['groups' => ['batch']]);
Type Safety:
Deserialization assumes the target class exists and is compatible with the input. Validate types or use DenormalizerAwareInterface for custom logic:
Serializer::deserialize($json, User::class, 'json', [
'object_to_populate' => $existingUser,
]);
Serializer::setDebug(true); // Logs normalization/denormalization steps
dd(Serializer::getContainer()->get('serializer')->getNormalizers()->getNormalizers());
encoders and normalizers in config/lara-asp-serializer.php match your use case. Missing encoders (e.g., json) will throw errors.Custom Encoders: Add support for new formats (e.g., XML, CSV) by extending the config:
'encoders' => [
'csv' => new \Symfony\Component\Serializer\Encoder\CsvEncoder(),
],
Then use:
Serializer::serialize($data, 'csv');
Middleware for API: Create a middleware to auto-serialize responses:
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response->isJson()) {
$data = $response->getData(true);
$response->setData(Serializer::serialize($data, 'json', ['groups' => ['api']]));
}
return $response;
}
Dynamic Group Resolution:
Override group resolution logic by binding a custom GroupResolver:
$serializer = Serializer::getContainer()->get('serializer');
$serializer->getNormalizers()->setGroupResolver(new CustomGroupResolver());
Event Listeners: Hook into serialization/deserialization events via Symfony’s event system:
$serializer->addSubscriber(new class implements SerializerSubscriberInterface {
public function hasMethods(string $format): bool { return true; }
public function getSubscribedMethods(): array { return ['onSerialize']; }
public function onSerialize(SerializeEvent $event) { /* ... */ }
});
How can I help you explore Laravel packages today?