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

Data Transformation And Serialization Laravel Package

arens-myzyri/data-transformation-and-serialization

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arens-myzyri/data-transformation-and-serializer
    

    Ensure your project meets the requirements (PHP 8.1+, Symfony 6.2+).

  2. First Use Case: Inject the DataTransformerInterface into a service/controller:

    use ArensMyzyri\DataTransformationAndSerializer\DataTransformerInterface;
    
    public function __construct(private DataTransformerInterface $transformer) {}
    
    // Transform a model to JSON
    $json = $this->transformer->transformModelToJson($model);
    
  3. Key Methods:

    • transformModelToJson($model) → Serializes a model to JSON.
    • transformJsonToModel($json, Model::class) → Deserializes JSON to a model.
    • transformArrayToModel($array, Model::class) → Converts an array to a model.
  4. Where to Look First:

    • Review the README for basic usage.
    • Check the tests for real-world examples.

Implementation Patterns

Core Workflows

  1. Model Serialization: Use transformModelToJson() for API responses or caching:

    $response = $this->transformer->transformModelToJson($user);
    return response()->json($response);
    
  2. Deserialization: Convert JSON/API payloads to Eloquent models:

    $userData = json_decode(request()->getContent(), true);
    $user = $this->transformer->transformJsonToModel($userData, User::class);
    
  3. Array-to-Model Conversion: Transform form submissions or legacy data:

    $formData = request()->all();
    $model = $this->transformer->transformArrayToModel($formData, Post::class);
    

Integration Tips

  • Symfony Serializer Compatibility: Leverage Symfony’s built-in normalization groups (e.g., @Groups({"api"})) for granular control over serialization.

  • Custom Transformers: Extend the package by implementing DataTransformerInterface or using Symfony’s Normalizer/Denormalizer interfaces.

  • Validation: Combine with Laravel’s Validator or Symfony’s Validator to sanitize data before/after transformation:

    $data = $this->transformer->transformJsonToModel($json, User::class);
    $validator = Validator::make($data->toArray(), User::$rules);
    
  • Caching Responses: Cache serialized JSON responses for performance:

    $cacheKey = 'user:'.$user->id;
    $json = Cache::remember($cacheKey, 3600, fn() =>
        $this->transformer->transformModelToJson($user)
    );
    
  • API Resource Integration: Use alongside Laravel’s JsonResource for hybrid serialization:

    $resource = new UserResource($user);
    $json = $this->transformer->transformModelToJson($resource);
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Conflicts:

    • The package requires Symfony components (e.g., Serializer). If your project uses Laravel without Symfony, ensure compatibility or mock dependencies during testing.
    • Fix: Use symfony/runtime to isolate Symfony dependencies if needed.
  2. Circular References:

    • Symfony’s serializer may fail on circular references (e.g., User->posts->author->user).
    • Fix: Use @MaxDepth or @Ignore attributes:
      #[Ignore]
      public function getPosts() { ... }
      
  3. Type Mismatches:

    • transformJsonToModel() assumes JSON keys match model properties exactly. Nested objects/arrays may fail silently.
    • Fix: Use transformArrayToModel() for more control or implement a custom denormalizer.
  4. Performance Overhead:

    • Serialization/deserialization adds latency. Cache results aggressively for frequent operations.
  5. Laravel-Specific Quirks:

    • Eloquent models with custom accessors/mutators may not serialize/deserialize as expected.
    • Fix: Use ->toArray() or ->jsonSerialize() to normalize data before transformation.

Debugging

  • Enable Symfony Debug: Configure Symfony’s serializer debug mode to inspect normalization:

    # config/packages/serializer.yaml
    framework:
        serializer:
            debug: true
    
  • Log Normalization Groups: Add debug logs to track which groups are applied:

    $this->transformer->transformModelToJson($model, ['groups' => ['api', 'debug']]);
    

Extension Points

  1. Custom Normalizers/Denormalizers: Register Symfony’s normalizers for custom types (e.g., Carbon instances):

    use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
    
    $normalizers = [
        new DateTimeNormalizer(),
        // ...
    ];
    $this->transformer->setNormalizers($normalizers);
    
  2. Event Listeners: Hook into Symfony’s serialize/deserialize events for pre/post-processing:

    $serializer->addSubscriber(new class implements SerializerSubscriberInterface {
        public function hasEvents(): bool { return true; }
        public function getSubscribedEvents(): array {
            return [
                Serializer::EVENT_SERIALIZE => 'onSerialize',
                Serializer::EVENT_DESERIALIZE => 'onDeserialize',
            ];
        }
    });
    
  3. Configuration Overrides: Override default serializer settings via dependency injection:

    $serializer = Serializer::create([
        'json' => ['ignore_unknown_fields' => false],
    ]);
    $this->transformer->setSerializer($serializer);
    

Pro Tips

  • Use for API Versioning: Leverage normalization groups to version API responses without breaking changes:

    // v1
    $json = $this->transformer->transformModelToJson($user, ['groups' => ['v1']]);
    
    // v2
    $json = $this->transformer->transformModelToJson($user, ['groups' => ['v2']]);
    
  • Batch Processing: Transform collections efficiently:

    $users = User::all();
    $json = $this->transformer->transformModelToJson($users); // Handles collections
    
  • Testing: Mock DataTransformerInterface in unit tests to isolate serialization logic:

    $this->mock(DataTransformerInterface::class)->shouldReceive('transformModelToJson')
        ->once()->andReturn('{"id":1}');
    
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.
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
atriumphp/atrium