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

Json Serializer Laravel Package

zumba/json-serializer

Serialize and unserialize PHP values to JSON (like serialize()), including scalars, arrays, objects, recursion, stdClass extra properties, nested data, and binary. Optional closure support via third party. PHP 7.2+; avoid untrusted input.

View on GitHub
Deep Wiki
Context7
## Getting Started
### **First Steps**
1. **Installation**
   ```bash
   composer require zumba/json-serializer:^3.2.4

The package is auto-discoverable in Laravel 5.5+ (no manual provider registration needed).

  1. Basic Usage

    use Zumba\JsonSerializer\JsonSerializer;
    
    $serializer = app(JsonSerializer::class);
    $data = ['name' => 'John', 'age' => 30, 'active' => true];
    
    // Serialize
    $json = $serializer->serialize($data);
    // '{"name":"John","age":30,"active":true}'
    
    // Unserialize
    $decoded = $serializer->unserialize($json);
    // ['name' => 'John', 'age' => 30, 'active' => true]
    
  2. First Use Case

    • API Responses: Replace json_encode() with $serializer->serialize() for consistent JSON formatting.
    • Caching: Serialize complex objects (e.g., Eloquent models) to store in Redis/Memcached.
    • Parent Class Properties: Fully supports serialization of private properties from both parent and child classes (fixed in v3.2.4).
    • Typed Properties: No more fatal errors when serializing objects with uninitialized typed properties (e.g., public string $name without initialization). Now defaults to null for uninitialized typed properties.
    • Security: Added SECURITY.md for best practices on input validation and output sanitization.

Implementation Patterns

Common Workflows

  1. Object Serialization (Including Parent/Child Class Properties)

    class ParentClass {
        private $secret = 'hidden';
    }
    
    class ChildClass extends ParentClass {
        public $name = 'Alice';
        private $privateData = 'child_secret';
    }
    
    $child = new ChildClass();
    $json = $serializer->serialize($child);
    // Now includes ALL private properties from parent AND child classes
    
  2. Handling Typed Properties (Fixed in v3.2.4)

    class User {
        public string $name; // No longer throws fatal error if uninitialized
        public int $age;
        public ?DateTime $createdAt; // Nullable types work too
    }
    
    $user = new User(); // No errors
    $json = $serializer->serialize($user);
    // '{"name":null,"age":null,"createdAt":null}'
    
  3. Custom Handlers for Special Types

    // Handle DateTime objects
    $serializer->setDateTimeHandler(function ($date) {
        return $date->format('Y-m-d H:i:s');
    });
    
    // Handle Carbon instances
    $serializer->setObjectHandler('Carbon\Carbon', function ($carbon) {
        return $carbon->toIso8601String();
    });
    
    // Handle circular references (safer with default handler)
    $serializer->setCircularReferenceHandler(function ($object, $path) {
        return "[Circular Reference: {$path}]";
    });
    
  4. Integration with Laravel

    • API Resources:
      public function toArray($request)
      {
          return $this->serializer->serialize($this->resource, [
              'exclude' => ['password', 'api_token'],
          ]);
      }
      
    • Middleware for Input Sanitization:
      public function handle($request, Closure $next)
      {
          $request->merge($this->serializer->unserialize($request->input('data')));
          return $next($request);
      }
      
    • Eloquent Model Casting:
      protected $casts = [
          'created_at' => 'datetime:Y-m-d H:i:s',
      ];
      
      // Serialize with custom format
      $json = $serializer->serialize($this)->setDateTimeHandler('Y-m-d H:i:s');
      
  5. Batch Processing with Typed Safety

    $users = User::all();
    $jsonArray = array_map(
        fn ($user) => $serializer->serialize($user),
        $users
    );
    // No fatal errors for uninitialized typed properties
    
  6. Closure Compatibility (v3.2.4)

    // Works seamlessly with opis/closure v4
    $serializer->setObjectHandler('Closure', function ($closure) {
        return 'Closure detected';
    });
    

Gotchas and Tips

Pitfalls

  1. Circular References

    • Default behavior now returns a placeholder ([Circular Reference: path]) instead of throwing an error.
    • Customize with setCircularReferenceHandler if needed.
  2. Private/Protected Properties

    • All private/protected properties (parent + child) are now serializable by default.
    • To exclude specific properties, use the exclude option:
      $json = $serializer->serialize($object, ['exclude' => ['secret']]);
      
  3. Uninitialized Typed Properties (Now Fixed)

    • Previously caused fatal errors. Now returns null for uninitialized typed properties (e.g., public string $name).
    • For strict validation, use:
      $serializer->setStrictTypedProperties(true); // Throws error if uninitialized
      
  4. Performance with Large Data

    • Avoid serializing deeply nested objects in loops. Use lazy loading or caching:
      $cached = cache()->remember("user_{$user->id}_serialized", now()->addHours(1), function () use ($user) {
          return $serializer->serialize($user);
      });
      
  5. Security Considerations (New in v3.2.4)

    • Review SECURITY.md for input validation and output sanitization.
    • Never unserialize untrusted data (use unserialize cautiously):
      $data = $serializer->unserialize($json, ['strict' => true]);
      

Debugging Tips

  • Enable Pretty Printing:
    $serializer->setPrettyPrint(true);
    $json = $serializer->serialize($data); // Indented JSON
    
  • Validate JSON Output:
    if (json_validate($serializer->serialize($data))) {
        // Safe to use
    }
    
  • Check for Typed Property Issues:
    try {
        $json = $serializer->serialize($user, ['strict' => true]);
    } catch (\TypeError $e) {
        // Handle or log typed property errors
    }
    
  • Log Serialization Paths (for circular references):
    $serializer->setCircularReferenceHandler(function ($object, $path) {
        Log::debug("Circular reference detected at: {$path}");
        return "[Circular]";
    });
    

Extension Points

  1. Custom Serializers

    • Implement Zumba\JsonSerializer\Contracts\Serializer for domain-specific logic.
    • Example:
      class UserSerializer implements Serializer {
          public function serialize($data) {
              // Custom logic
          }
      }
      
  2. Closure Support (v3.2.4)

    • Register handlers for closures:
      $serializer->setObjectHandler('Closure', function ($closure) {
          return 'Closure serialized';
      });
      
  3. Configuration

    • Override defaults in config/zumba-json-serializer.php:
      'default_handlers' => [
          'App\Models\User' => 'App\Serializers\UserSerializer',
      ],
      'strict_typed_properties' => env('JSON_SERIALIZER_STRICT', false),
      

Pro Tips

  • Use for API Versioning:
    $v1Serializer = new JsonSerializer(['version' => '1.0', 'exclude' => ['deprecated_field']]);
    $v2Serializer = new JsonSerializer(['version' => '2.0']);
    
  • Combine with Laravel’s Response:
    return response()->json(
        $serializer->serialize($data),
        200,
        ['Content-Type' => 'application/json; charset=utf-8']
    );
    
  • Test Edge Cases:
    • Test with null, false, NaN, Infinity, and resource types.
    • Use setStrictTypedProperties(true) in tests to catch uninitialized typed properties.
  • Parent/Child Class Serialization:
    • Explicitly define handlers for complex inheritance:
      $serializer->setObjectHandler('App\Models\ParentClass', function ($obj) {
          return array_merge(
              get_object_vars($obj),
              ['inherited_data' => 'custom_value']
          );
      });
      
  • Performance Optimization:
    • Cache serialized results for frequently accessed data:
      $serialized = cache()->remember("serialized_{$key
      
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.
calliostro/spotify-bundle
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