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

aescarcha/serializer

Symfony bundle that simplifies entity serialization using symfony/serializer, with optional fallback loading from Doctrine when relations or data aren’t initialized. Installs via Composer and registers as a service and bundle.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aescarcha/serializer
    

    Ensure your project uses Symfony 4+ (or 3.x with Flex) and Doctrine ORM.

  2. Register the Bundle Add to config/bundles.php:

    return [
        // ...
        Aescarcha\SerializerBundle\AescarchaSerializerBundle::class => ['all' => true],
    ];
    
  3. First Use Case Inject the serializer service into a controller or service:

    use Aescarcha\SerializerBundle\Serializer\SerializerService;
    
    class MyController extends AbstractController
    {
        public function __construct(private SerializerService $serializer)
        {
        }
    
        public function serializeEntity(EntityInterface $entity): string
        {
            return $this->serializer->serialize($entity);
        }
    }
    
  4. Key Configuration The bundle auto-configures with Doctrine ORM. No additional services.yml is needed in Symfony 4+ (Flex handles it). For manual setups, ensure:

    # config/services.yaml
    services:
        Aescarcha\SerializerBundle\Serializer\SerializerService:
            arguments:
                $entityManager: '@doctrine.orm.entity_manager'
    

Implementation Patterns

Core Workflows

  1. Basic Serialization Serialize an entity to JSON/array with default groups:

    $serialized = $this->serializer->serialize($entity, 'json');
    // or
    $serialized = $this->serializer->toArray($entity);
    
  2. Custom Groups Use Symfony’s #[Groups] attribute or pass groups explicitly:

    $this->serializer->serialize($entity, 'json', ['groups' => ['api']]);
    
  3. Fallback to Database If an entity is missing data (e.g., lazy-loaded relations), the bundle fetches missing fields from the DB:

    $this->serializer->serialize($entity, 'json', ['fallback_to_db' => true]);
    
  4. Deserialization Reconstruct an entity from serialized data:

    $entity = $this->serializer->deserialize($serializedData, EntityClass::class, 'json');
    

Integration Tips

  • API Platform Integration Override API Platform’s default serializer by configuring the bundle’s service as the primary serializer in config/packages/api_platform.yaml:

    api_platform:
        serializer:
            service: aescarcha.serializer
    
  • Event Listeners Attach listeners to pre/post-serialize events for custom logic:

    $serializer->addSerializerListener(new CustomSerializeListener());
    
  • Normalizers Extend functionality by registering custom normalizers:

    $serializer->addNormalizer(new CustomNormalizer());
    
  • Circular References Handle circular references with ignore_circular_references:

    $this->serializer->serialize($entity, 'json', ['ignore_circular_references' => true]);
    

Gotchas and Tips

Pitfalls

  1. Doctrine Dependency

    • The bundle requires Doctrine ORM. If missing, serialization will fail with EntityManager not found.
    • Fix: Ensure doctrine/orm is installed and configured.
  2. Fallback to DB Overhead

    • Enabling fallback_to_db triggers additional queries for missing data, which can impact performance.
    • Tip: Use sparingly or cache results (e.g., with Symfony\Contracts\Cache\CacheInterface).
  3. Test Environment Issues

    • Tests in the repo assume pre-configured entities/repositories. Do not rely on them for integration testing.
    • Workaround: Mock the SerializerService in tests:
      $this->serializer = $this->createMock(SerializerService::class);
      $this->serializer->method('serialize')->willReturn('{"id":1}');
      
  4. Attribute Overrides

    • The bundle prioritizes #[Groups] over manual group configurations. Explicitly pass groups to override:
      $this->serializer->serialize($entity, 'json', ['groups' => ['override']]);
      
  5. Symfony 5+ Deprecations

    • The bundle may not fully support Symfony 5.3+ features (e.g., #[AsArrayProperty]).
    • Tip: Check the underlying symfony/serializer version for compatibility.

Debugging

  • Enable Serializer Debugging Add this to config/packages/dev/serializer.yaml:

    framework:
        serializer:
            debug: true
    

    Logs will show normalization groups and circular references.

  • Common Errors

    Error Cause Solution
    No serializer found Missing #[Groups] or custom normalizer Add #[Groups] or register a normalizer.
    EntityManager not found Doctrine not installed/configured Install doctrine/orm and update config.
    Circular reference detected Infinite recursion in entities Use ignore_circular_references: true.

Extension Points

  1. Custom Serializer Extend SerializerService to add domain-specific logic:

    class CustomSerializer extends SerializerService
    {
        public function serializeWithExtraData($entity, $format, array $context = [])
        {
            $context['extra'] = $this->getExtraData($entity);
            return parent::serialize($entity, $format, $context);
        }
    }
    
  2. Dynamic Groups Generate groups dynamically based on user roles:

    $groups = $this->security->isGranted('ROLE_ADMIN') ? ['admin', 'api'] : ['api'];
    $this->serializer->serialize($entity, 'json', ['groups' => $groups]);
    
  3. Cache Serialized Output Cache results to avoid repeated serialization:

    $cacheKey = md5($entity->getId().serialize($groups));
    $serialized = $cache->get($cacheKey, function() use ($entity, $groups) {
        return $this->serializer->serialize($entity, 'json', ['groups' => $groups]);
    });
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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