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

apie/serializer

Apie Serializer converts domain objects to stored/customer-facing data and back. Similar to Symfony Serializer but uses ApieSerializerContext for recursive calls. Supports normalize/denormalize, encoding/decoding, and easy extension via custom Normalizer and Denormalizer interfaces.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require apie/serializer
    

    Add to composer.json if using a monorepo or custom package structure.

  2. Basic Usage

    use Apie\Serializer\Serializer;
    
    $serializer = new Serializer();
    $data = ['name' => 'John', 'age' => 30];
    $json = $serializer->serialize($data);
    $decoded = $serializer->deserialize($json, 'array');
    
  3. Laravel Integration Bind the serializer to the container in AppServiceProvider:

    $this->app->singleton(Serializer::class, function ($app) {
        return new Serializer();
    });
    

    Inject via constructor:

    public function __construct(private Serializer $serializer) {}
    
  4. First Use Case Convert Eloquent models to JSON with custom rules:

    $user = User::find(1);
    $serialized = $serializer->serialize($user, [
        'name' => ['property' => 'full_name'],
        'email' => ['property' => 'email_address'],
    ]);
    

Implementation Patterns

Common Workflows

  1. Model Serialization

    $serializer->serialize($model, [
        'id' => ['property' => 'uuid'],
        'created_at' => ['format' => 'Y-m-d'],
    ]);
    
  2. Nested Objects

    $serializer->serialize($order, [
        'items' => [
            'type' => 'collection',
            'items' => [
                'product_id' => ['property' => 'product.uuid'],
                'quantity' => ['property' => 'quantity'],
            ],
        ],
    ]);
    
  3. Deserialization

    $data = $serializer->deserialize($json, 'array', [
        'user' => ['type' => 'object', 'properties' => [...]],
    ]);
    
  4. API Responses

    return response()->json($serializer->serialize($data, $rules), 200, [], JSON_PRETTY_PRINT);
    

Integration Tips

  • Form Requests: Use deserialize() to validate and transform incoming JSON:
    $validated = $serializer->deserialize($request->json(), 'array', $rules);
    
  • API Resources: Extend Laravel’s JsonResource to use the serializer for consistent output:
    public function toArray($request)
    {
        return $this->serializer->serialize($this->resource, $this->rules);
    }
    
  • Caching: Cache serialized responses for performance:
    $cacheKey = 'user:'.$user->id;
    $serialized = Cache::remember($cacheKey, now()->addHours(1), function () use ($user) {
        return $serializer->serialize($user);
    });
    

Gotchas and Tips

Pitfalls

  1. Circular References

    • The serializer may fail on circular references (e.g., User->orders->user).
    • Fix: Use ['ignore_circular' => true] or implement a custom resolver.
  2. Type Mismatches

    • Deserializing into wrong types (e.g., JSON string into int) throws exceptions.
    • Fix: Validate types in rules or use try-catch:
      try {
          $data = $serializer->deserialize($json, 'array');
      } catch (SerializationException $e) {
          return response()->json(['error' => 'Invalid data'], 400);
      }
      
  3. Default Values

    • Missing properties default to null. Use default in rules:
      ['age' => ['default' => 18]]
      
  4. Performance

    • Deeply nested objects may impact performance.
    • Tip: Use ['max_depth' => 5] to limit recursion.

Debugging

  • Enable Verbose Errors

    $serializer = new Serializer(['verbose_errors' => true]);
    

    Logs detailed errors for invalid rules or missing properties.

  • Inspect Rules Validate rules before serialization:

    $serializer->validateRules($data, $rules);
    

Extension Points

  1. Custom Serializers Implement Apie\Serializer\Contracts\SerializerInterface for domain-specific logic:

    class CustomSerializer implements SerializerInterface {
        public function serialize($data, array $rules = []): string {
            // Custom logic
        }
    }
    
  2. Rule Extensions Add custom rule types:

    $serializer->addRuleType('slug', function ($value) {
        return Str::slug($value);
    });
    

    Usage:

    ['slug' => ['type' => 'slug', 'property' => 'name']]
    
  3. Event Hooks Listen for serializing and deserializing events (if supported in future versions):

    $serializer->on('serializing', function ($data, $rules) {
        // Pre-process data
    });
    

Config Quirks

  • Default Rules: Override defaults in the constructor:
    $serializer = new Serializer([
        'default_rules' => ['id' => ['property' => 'uuid']],
    ]);
    
  • Date Handling: Use ['format' => 'Y-m-d H:i:s'] for custom date formats. Default is ISO-8601.
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor