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

nilportugues/serializer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nilportugues/serializer
    

    Add the service provider to config/app.php under providers:

    NilPortugues\Serializer\SerializerServiceProvider::class,
    
  2. Basic Usage:

    use NilPortugues\Serializer\Serializer;
    
    $serializer = app(Serializer::class);
    $data = ['name' => 'John', 'age' => 30, 'active' => true];
    
    // Serialize to JSON
    $json = $serializer->serialize($data, 'json');
    echo $json; // '{"name":"John","age":30,"active":true}'
    
    // Unserialize from JSON
    $unserialized = $serializer->unserialize($json, 'json');
    print_r($unserialized); // ['name' => 'John', ...]
    
  3. First Use Case: Convert Eloquent models to JSON for API responses:

    $user = User::find(1);
    $responseData = $serializer->serialize($user, 'json');
    return response()->json($responseData);
    

Implementation Patterns

Common Workflows

  1. API Response Handling:

    public function show(User $user)
    {
        return response()->json(
            $this->serializer->serialize($user, 'json', [
                'attributes' => ['id', 'name', 'email'],
                'relations' => ['posts']
            ])
        );
    }
    
  2. Caching Serialized Data:

    $cacheKey = 'user:1:serialized';
    $serialized = cache($cacheKey);
    if (!$serialized) {
        $user = User::find(1);
        $serialized = $this->serializer->serialize($user, 'json');
        cache()->put($cacheKey, $serialized, now()->addHour());
    }
    
  3. Form Request Validation:

    public function rules()
    {
        return [
            'user_data' => 'required|string',
        ];
    }
    
    public function validated($data)
    {
        $unserialized = $this->serializer->unserialize($data['user_data'], 'json');
        return $unserialized;
    }
    

Integration Tips

  • Custom Serialization: Register custom handlers for specific classes:

    $serializer->addHandler('App\Models\CustomModel', function ($model) {
        return ['id' => $model->id, 'custom_field' => $model->customField];
    });
    
  • Middleware for API: Create middleware to auto-serialize responses:

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($response->isJson()) {
            $data = $response->getData(true);
            $serialized = $this->serializer->serialize($data, 'json');
            $response->setContent($serialized);
        }
        return $response;
    }
    
  • Queue Jobs: Serialize job payloads to reduce memory usage:

    $job = new ProcessOrder($order->id);
    $job->setSerializedPayload($this->serializer->serialize($order, 'json'));
    dispatch($job);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Last release in 2018—check for modern alternatives like spatie/array-to-xml, jenssegers/date, or Laravel’s built-in json_encode()/json_decode().
    • May lack PHP 8+ compatibility or security patches.
  2. Performance Overhead:

    • Serialization/unserialization adds CPU cycles. Benchmark for high-traffic APIs.
    • Avoid deep nesting in serialized data (e.g., recursive objects).
  3. Security Risks:

    • Unserialize operations can execute arbitrary code if input isn’t trusted. Never unserialize user-provided data blindly.
    • Example of safe usage:
      $trustedData = $this->serializer->unserialize($input, 'json', [
          'allowed_formats' => ['json', 'array'], // Restrict formats
      ]);
      
  4. Configuration Quirks:

    • Default handlers may not cover all edge cases (e.g., DateTime, Carbon).
    • Override defaults explicitly:
      $serializer->setDefaultHandlers([
          'datetime' => function ($date) {
              return $date->format('Y-m-d H:i:s');
          },
      ]);
      

Debugging Tips

  1. Validate Serialized Output:

    $serialized = $this->serializer->serialize($data, 'json');
    $unserialized = $this->serializer->unserialize($serialized, 'json');
    if (!hash_equals($serialized, $this->serializer->serialize($unserialized, 'json'))) {
        throw new \RuntimeException('Serialization round-trip failed!');
    }
    
  2. Log Custom Handlers: Add debug logs for custom serializers:

    $serializer->addHandler('App\Models\Post', function ($post) {
        \Log::debug('Serializing Post', ['post' => $post->toArray()]);
        return $post->toArray();
    });
    
  3. Handle Circular References: The package may not handle circular references (e.g., User->posts->author->user). Use a workaround:

    $serializer->setOption('circular_reference_handler', function ($object) {
        return '[Circular Reference]';
    });
    

Extension Points

  1. Add Custom Formats: Extend support for formats like YAML or MessagePack:

    $serializer->addFormat('yaml', function ($data) {
        return \Spatie\ArrayToXml\ArrayToXml::convert($data);
    }, function ($string) {
        return yaml_parse($string);
    });
    
  2. Event-Based Serialization: Listen to serialization events (if supported) to modify output dynamically:

    $serializer->on('serializing', function ($data, $format) {
        if ($format === 'json') {
            $data['timestamp'] = now()->toIso8601String();
        }
    });
    
  3. Fallback for Missing Handlers: Provide a fallback for unsupported types:

    $serializer->setFallbackHandler(function ($value) {
        return is_object($value) ? get_class($value) : $value;
    });
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle