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

Serialization Laravel Package

amphp/serialization

AMPHP serialization tools for IPC and storage in PHP. Provides a Serializer interface with JSON, native PHP serialize/unserialize, and passthrough implementations, plus optional payload compression via a wrapping serializer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require amphp/serialization
    

    Ensure your project uses PHP 7.4+ (hard requirement).

  2. First Use Case: Serialize a complex object (e.g., a closure or resource) for IPC in an AMPHP-based worker:

    use Amp\Serialization\NativeSerializer;
    
    $serializer = new NativeSerializer();
    $data = [
        'task' => fn() => 'async-work',
        'resource' => fopen('php://memory', 'r+')
    ];
    $serialized = $serializer->serialize($data);
    
  3. Where to Look First:

    • Serializer interface: Core contract for serialize()/unserialize().
    • NativeSerializer: For full PHP type support (closures, resources).
    • CompressingSerializer: Wrap any serializer for payload size reduction.
    • Exceptions: SerializationException for debugging.

Implementation Patterns

Usage Patterns

  1. IPC Workflows:

    • Worker-to-worker communication via Unix sockets or shared memory:
      $serializer = new CompressingSerializer(new NativeSerializer());
      $payload = $serializer->serialize($taskData);
      socket_write($socket, $payload);
      
    • Deserialize in another fiber:
      $data = $serializer->unserialize(socket_read($socket));
      
  2. AMPHP Integration:

    • Async streams: Serialize closures/resources for deferred execution:
      $serializer = new NativeSerializer();
      $closure = fn() => $serializer->unserialize($storedData);
      $stream->write($serializer->serialize($closure));
      
  3. Hybrid Serialization:

    • Combine with Laravel’s tools (e.g., JSON for APIs, Native for IPC):
      $serializer = $isIpc ? new NativeSerializer() : new JsonSerializer();
      
  4. Compression Strategy:

    • Benchmark payload sizes before/after CompressingSerializer:
      $compressedSize = strlen($serializer->serialize($data));
      $uncompressedSize = strlen((new NativeSerializer())->serialize($data));
      

Workflows

  1. Queue Jobs (AMPHP Workers):

    • Serialize job payloads with compression for high-throughput workers:
      $job = new AsyncJob($data);
      $serializer = new CompressingSerializer(new NativeSerializer());
      $payload = $serializer->serialize($job);
      dispatch($payload)->onQueue('async');
      
  2. Cache Layer:

    • Store large objects (e.g., compiled templates) with compression:
      Cache::put('template:large', $serializer->serialize($template), now()->addHours(1));
      
  3. Shared Memory:

    • Use NativeSerializer for cross-process object sharing (e.g., Amp\Artisan\Process):
      $sharedData = $serializer->serialize($config);
      shared_memory_write($segment, $sharedData);
      

Integration Tips

  1. Laravel Service Provider: Bind serializers as singletons for dependency injection:

    $this->app->singleton('serializer.native', fn() => new NativeSerializer());
    $this->app->singleton('serializer.compressed', fn($app) =>
        new CompressingSerializer($app->make('serializer.native'))
    );
    
  2. Middleware for IPC: Wrap AMPHP IPC requests/responses:

    public function handle($request, Closure $next) {
        $data = $serializer->unserialize($request->getContent());
        $response = $next($data);
        return response($serializer->serialize($response));
    }
    
  3. Fallback Strategy: Implement a decorator to fallback to JSON for unsupported types:

    class SafeSerializer implements Serializer {
        public function unserialize(string $data) {
            try {
                return $this->serializer->unserialize($data);
            } catch (SerializationException $e) {
                return json_decode($data, true);
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. PHP 7.4+ Hard Requirement:

    • Fails on PHP 8.x: #[Override] attributes may conflict with Laravel’s attributes (e.g., #[Cacheable]).
    • Workaround: Isolate AMPHP code to a PHP 7.4-compatible environment or fork the package.
  2. Unserialize Security:

    • NativeSerializer is unsafe for untrusted data. Always validate:
      if (!in_array(gettype($data), ['array', 'object', 'string'])) {
          throw new \RuntimeException('Unsafe data type');
      }
      
  3. Circular References:

    • NativeSerializer may fail on circular references. Use JsonSerializer as a fallback:
      try {
          return $nativeSerializer->unserialize($data);
      } catch (SerializationException $e) {
          return json_decode($data, true);
      }
      
  4. Resource Leaks:

    • Serializing resources (e.g., file handles) may cause leaks. Close resources before serialization:
      fclose($resource);
      $serialized = $serializer->serialize(['resource' => $resource]);
      
  5. Compression Overhead:

    • CompressingSerializer adds CPU overhead. Benchmark for small payloads (<1KB):
      $microtime = microtime(true);
      $compressed = $compressedSerializer->serialize($data);
      $time = microtime(true) - $microtime;
      // Abort if compression adds >10% latency
      

Debugging

  1. SerializationException:

    • Check for unsupported types (e.g., DateTimeImmutable, Closure):
      catch (SerializationException $e) {
          Log::error('Unsupported type: ' . gettype($data), ['exception' => $e]);
      }
      
  2. Corrupted Data:

    • Validate serialized strings before deserialization:
      if (!is_string($data) || strlen($data) < 10) {
          throw new \InvalidArgumentException('Invalid serialized data');
      }
      
  3. Fiber Context:

    • Ensure serializers are fiber-safe (they are, but test in async contexts):
      Amp\async(function() use ($serializer, $data) {
          $serialized = $serializer->serialize($data);
          // ...
      });
      

Config Quirks

  1. Compression Level:

    • CompressingSerializer uses default zlib compression. Adjust via constructor:
      $compressor = new \Amp\Serialization\CompressingSerializer(
          $serializer,
          ['level' => 9] // Max compression
      );
      
  2. Native Serializer Quirks:

    • Class names are serialized: Ensure all classes are autoloadable.
    • Magic properties: May not serialize correctly. Use __serialize()/__unserialize().
  3. PassthroughSerializer:

    • Only use for already-serialized strings (e.g., from external systems):
      $passthrough = new PassthroughSerializer();
      $data = $passthrough->unserialize($externalString);
      

Extension Points

  1. Custom Serializers:

    • Implement Serializer for domain-specific logic:
      class EloquentSerializer implements Serializer {
          public function serialize($model) {
              return serialize($model->toArray());
          }
          public function unserialize(string $data) {
              return Model::hydrate(unserialize($data));
          }
      }
      
  2. Decorator Pattern:

    • Extend existing serializers (e.g., add logging):
      class LoggingSerializer implements Serializer {
          public function serialize($data) {
              Log::debug('Serializing', ['data' => gettype($data)]);
              return $this->serializer->serialize($data);
          }
      }
      
  3. Attribute-Based Serialization:

    • Use #[Override] for custom logic (PHP 7.4+ only):
      #[Override]
      public function serialize($data) {
          // Custom logic
      }
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle