spiral/serializer
A PHP serialization library from Spiral: serialize/deserialize objects and arrays with configurable mappings and type handling, designed to integrate with Spiral components and support common data formats and transformation workflows.
Install the package via Composer: composer require spiral/serializer. This is a Spiral Framework component—ensure your project uses Spiral as the base stack before proceeding. The primary entry point is the Spiral\Serializer\Serializer class. Start with basic usage in a service or controller:
use Spiral\Serializer\Serializer;
use Spiral\Serializer\Encoder\JsonEncoder;
use Spiral\Serializer\Normalizer\ObjectNormalizer;
$serializer = new Serializer([new JsonEncoder()], [new ObjectNormalizer()]);
$json = $serializer->serialize($dto);
$dto = $serializer->deserialize($json, UserDTO::class);
Look first at the src/ directory for core interfaces (SerializerInterface, NormalizerInterface, EncoderInterface) and built-ins (JsonEncoder, ObjectNormalizer). These define the default behavior for common PHP types (objects, arrays, DateTime, etc.).
MsgPackEncoder) while reusing normalization rules—great for high-performance internal services.NormalizerInterface for types like Money, EmailAddress, or Enum to ensure consistent conversion (e.g., Money → ['amount' => 1000, 'currency' => 'USD']).SerializerInterface in Spiral’s DI container and inject it everywhere—enforces consistency across controllers, workers, and job handlers.ObjectNormalizer will hit infinite recursion on bidirectional relations (e.g., parent ↔ child) unless you configure a handler:
$context = (new SerializerContext())
->withCircularReferenceHandler(fn ($object) => ['id' => $object->getId()]);
$serializer->serialize($entity, ContextInterface::NORMALIZER => $context);
deserialize($data, SomeInterface::class) will fail. Always use concrete DTOs or classes with public properties / setters.@Serializer\SerializedName()—field names must match exactly, or you override via custom normalizers.serialize()—they may trigger lazy loads or throw "incomplete object" errors. Materialize data first (e.g., via repository projections or DTO mappers).SerializerContext for format-specific rules:
$context = (new SerializerContext())
->withDateTimeFormat('Y-m-d\TH:i:sP')
->withGroups(['api', 'public']);
AbstractNormalizer or wrap JsonEncoder to add cross-cutting concerns (e.g., redact password, ssn fields, or log serialization events for debugging).How can I help you explore Laravel packages today?