andrew-gos/serializer
Extensible PHP 8.2+ serializer that normalizes arrays/objects and encodes to JSON or XML. Register custom normalizers and encoders via a configurable Serializer. Pure encoders avoid mutating input and handle XML duplication/circular references.
SerializerFactory and Serializer classes can be easily integrated into Laravel’s service provider bootstrapping.Response::json()) by intercepting Illuminate\Http\Response or using middleware.App\Models\User) can replace Laravel’s built-in toArray()/toJson() methods.Illuminate\Queue\SerializesModels).Illuminate\Support\Str::uuid() for IDs).json_encode().Arrayable)?json_encode() or throw exceptions?Response::json() with Serializer::serialize($data, 'json') for consistent output.Illuminate\Database\Eloquent\Concerns\HasAttributes to use custom normalizers.Serializer instead of Laravel’s defaults.Serializer component, easing adoption for teams familiar with Symfony’s ecosystem.Http\Tests\TestResponse to verify serialized outputs match expectations.toArray()/toJson() with custom normalizers for 1–2 Eloquent models.json_encode().Response::json() calls in controllers.toJson() methods in favor of the package’s normalizers.symfony/serializer is not a dependency).spatie/array-to-xml or nesbot/carbon (Carbon instances may need custom normalizers).composer require andrew-gos/serializer).SerializerFactory in AppServiceProvider.NormalizerRegistry class to map Laravel types (e.g., App\Models\User) to custom normalizers.$serializer->addNormalizer(
App\Models\User::class,
fn (User $user) => $user->toArray() // or custom logic
);
json, xml) in the service provider.App\Exceptions\Handler to serialize errors using the package.public function handle($request, Closure $next) {
$response = $next($request);
if ($response->isJson()) {
$data = $response->getData();
$serialized = $this->serializer->serialize($data, 'json');
$response->setContent($serialized);
}
return $response;
}
FallbackSerializer class that delegates to json_encode() for unsupported types.json_encode(); minimal overhead.Illuminate\Support\Facades\Cache::remember()).catch-all normalizer:
$serializer->addNormalizer(
'default',
fn ($data) => is_object($data) ? get_object_vars($data) : $data
);
JsonEncoder::setMaxDepth() or Laravel’s Illuminate\Support\Str::uuid() for IDs.memory_limit. Implement a max_depth parameter for encoders.Serializer interface for all DTOs/models.app/Normalizers/).config('features.serializer_enabled') to toggle the package.config('app.fallback_serializer') to revert to native methods.How can I help you explore Laravel packages today?