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 Bundle Laravel Package

anzusystems/serializer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

This package, SerializerBundle, is a Laravel-friendly wrapper for Symfony's Serializer component, enabling seamless JSON/XML serialization/deserialization. To start:

  1. Install via Composer: composer require anzusystems/serializer-bundle
  2. Publish config: php artisan vendor:publish --provider="AnzuSystems\SerializerBundle\SerializerServiceProvider"
  3. Register the service provider in config/app.php under providers.
  4. Use the facade \AnzuSystems\SerializerBundle\Facades\Serializer for basic operations:
    $serialized = \Serializer::serialize($object, 'json');
    $object = \Serializer::deserialize($serialized, 'App\Model', 'json');
    
    First use case: Convert Eloquent models to/from JSON for APIs or storage.

Implementation Patterns

Core Workflows

  1. Model Serialization:

    $user = User::find(1);
    $serialized = \Serializer::serialize($user, 'json', [
        'groups' => ['user:public'] // Uses Symfony's @Groups annotations
    ]);
    
    • Leverage @Groups annotations in models for granular control:
      class User {
          /** @Groups({"user:public"}) */
          public $name;
      }
      
  2. Request/Response Handling:

    • Automatically serialize API responses:
      use AnzuSystems\SerializerBundle\Serializer;
      
      return response()->json(Serializer::serialize($data, 'json'));
      
  3. Deserialization:

    • Parse JSON/XML into PHP objects:
      $data = \Serializer::deserialize($json, 'App\Dto\UserDto', 'json');
      
  4. Custom Formats:

    • Extend with new formats (e.g., CSV) by implementing SerializerInterface.

Integration Tips

  • Laravel HTTP Messages: Use with Symfony\Component\HttpFoundation\Response for consistent serialization.
  • Validation: Combine with Laravel Validation for DTOs:
    $dto = \Serializer::deserialize($request->json(), UserDto::class, 'json');
    $validator = Validator::make($dto->toArray(), UserDto::$rules);
    
  • Caching: Cache serialized output for performance:
    $cacheKey = 'user:'.$user->id;
    $serialized = Cache::remember($cacheKey, now()->addHours(1), fn() =>
        \Serializer::serialize($user, 'json')
    );
    

Gotchas and Tips

Breaking Changes (6.0.0)

  • Symfony 8 Compatibility: This release resolves deprecations for Symfony 8, meaning:
    • If using Symfony 8, ensure your Laravel app (or dependencies) aligns with Symfony 8’s requirements (PHP 8.1+ recommended).
    • No direct API changes, but internal dependencies may affect custom serializers or formatters.
    • Action: Update symfony/serializer to ^6.0 if not already done:
      composer require symfony/serializer:^6.0
      

Common Pitfalls

  1. Annotation Processing:

    • Forgetting to enable annotation autoloading (e.g., doctrine/annotations for PHP annotations).
    • Fix: Ensure autoload-dev includes annotations in composer.json:
      "autoload-dev": {
          "psr-4": { "App\\": "app/" },
          "classmap": ["vendor/doctrine/annotations/lib/DocBlock"]
      }
      
  2. Circular References:

    • Serializing objects with circular references (e.g., User->posts->author->user) throws errors.
    • Solution: Use max_depth option:
      \Serializer::serialize($user, 'json', ['max_depth' => 2]);
      
  3. Performance:

    • Serializing large collections (e.g., 10K+ records) can be slow.
    • Tip: Use chunking or lazy serialization:
      $serializer = \Serializer::getSerializer();
      $serialized = $serializer->serialize($collection->take(100), 'json');
      
  4. Custom Normalizers:

    • Overriding default normalizers requires implementing Symfony\Component\Serializer\Normalizer\NormalizerInterface.
    • Tip: Register custom normalizers in the config:
      'serializer' => [
          'normalizers' => [
              App\Normalizer\CustomNormalizer::class,
          ],
      ],
      

Debugging Tips

  • Enable Debug Mode: Temporarily set 'debug' => true in config to log serialization issues.
  • Check Serialized Output: Use json_last_error() or simplexml_load_string() to validate output:
    $serialized = \Serializer::serialize($object, 'json');
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \RuntimeException('Serialization failed');
    }
    
  • Inspect Groups: Verify @Groups annotations are applied:
    $metadata = \Serializer::getMetadataFactory()->getMetadataFor(App\User::class);
    print_r($metadata->getGroups());
    

Extension Points

  1. Add New Formats:

    • Implement Symfony\Component\Serializer\Encoder\EncoderInterface for custom formats (e.g., MessagePack).
    • Register in config:
      'serializer' => [
          'encoders' => [
              App\Encoder\MessagePackEncoder::class,
          ],
      ],
      
  2. Event Listeners:

    • Listen to serializer.normalize or serializer.denormalize events for pre/post-processing:
      \Serializer::addListener('serializer.normalize', function ($event) {
          $event->getObject()->setHiddenAttribute(true);
      });
      
  3. Laravel Service Providers:

    • Bind custom serializers to the container:
      $this->app->bind(\SerializerInterface::class, function () {
          return new App\CustomSerializer();
      });
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware