Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Serializer Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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.).

Implementation Patterns

  • DTO layer validation: Deserialize API payloads directly into typed DTOs with validation hooks—ideal for request validation before domain processing.
  • Caching structured data: Serialize complex nested structures (e.g., hydrated repositories, nested collections) to cache stores (Redis, file), then reconstruct them without manual reconstruction logic.
  • Custom encoders for internal formats: Swap JSON for MessagePack or YAML by injecting alternate encoders (e.g., MsgPackEncoder) while reusing normalization rules—great for high-performance internal services.
  • Domain-aware normalizers: Implement NormalizerInterface for types like Money, EmailAddress, or Enum to ensure consistent conversion (e.g., Money['amount' => 1000, 'currency' => 'USD']).
  • Global serializer instance: Register SerializerInterface in Spiral’s DI container and inject it everywhere—enforces consistency across controllers, workers, and job handlers.

Gotchas and Tips

  • No circular reference protection by default: The 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);
    
  • Deserialization requires exact concrete types: deserialize($data, SomeInterface::class) will fail. Always use concrete DTOs or classes with public properties / setters.
  • No annotation support out-of-the-box: Unlike Symfony Serializer or JMS, there’s no @Serializer\SerializedName()—field names must match exactly, or you override via custom normalizers.
  • Performance pitfalls with ORM proxies: Avoid passing Doctrine entity proxies directly to serialize()—they may trigger lazy loads or throw "incomplete object" errors. Materialize data first (e.g., via repository projections or DTO mappers).
  • Context customization is key: Leverage SerializerContext for format-specific rules:
    $context = (new SerializerContext())
        ->withDateTimeFormat('Y-m-d\TH:i:sP')
        ->withGroups(['api', 'public']);
    
  • Extensibility tip: Extend AbstractNormalizer or wrap JsonEncoder to add cross-cutting concerns (e.g., redact password, ssn fields, or log serialization events for debugging).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport