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

Laminas Hydrator Laravel Package

laminas/laminas-hydrator

Laminas Hydrator provides flexible tools to hydrate and extract data between arrays and objects. Includes hydrator strategies, naming conventions, and integration helpers for forms and domain models, supporting multiple hydrator implementations and extensions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require laminas/laminas-hydrator
    

    For Laravel, use laminas/laminas-hydrator in composer.json or via composer require.

  2. Basic Hydration

    use Laminas\Hydrator\ClassMethodsHydrator;
    
    $hydrator = new ClassMethodsHydrator();
    $data = ['name' => 'John', 'age' => 30];
    $user = new User(); // Assume User has `setName()` and `setAge()` methods
    $hydrator->hydrate($data, $user);
    
  3. Basic Extraction

    $extracted = $hydrator->extract($user);
    // Returns: ['name' => 'John', 'age' => 30]
    

Where to Look First

First Use Case: API Request/Response Mapping

// In a Laravel controller:
public function store(Request $request) {
    $hydrator = app(ClassMethodsHydrator::class);
    $data = $request->validate()->all();
    $user = new User();
    $hydrator->hydrate($data, $user);
    $user->save();
    return response()->json($hydrator->extract($user));
}

Implementation Patterns

Core Workflows

  1. Hydration (Array → Object)

    • Use ClassMethodsHydrator for objects with setX()/getX() methods.
    • Use ReflectionHydrator for dynamic property mapping (no methods required).
    $hydrator = new ReflectionHydrator();
    $hydrator->hydrate(['email' => 'john@example.com'], $user);
    
  2. Extraction (Object → Array)

    • Default behavior mirrors hydration (e.g., getX()x).
    • Customize with NamingStrategy (e.g., camelCase ↔ snake_case).
    $hydrator->setNamingStrategy(new \Laminas\Hydrator\NamingStrategy\UnderscoreNamingStrategy());
    $extracted = $hydrator->extract($user); // ['first_name' => 'John']
    
  3. Nested Objects

    • Use AggregateHydrator to chain hydrators for nested structures.
    $addressHydrator = new ClassMethodsHydrator();
    $userHydrator = new AggregateHydrator();
    $userHydrator->add($addressHydrator, 'address'); // Maps 'address' → Address object
    $userHydrator->hydrate($data, $user);
    
  4. Filters (Selective Mapping)

    • Exclude/include properties dynamically.
    $hydrator->addFilter('exclude', new \Laminas\Hydrator\Filter\MethodMatchFilter('isSensitive'));
    

Laravel-Specific Patterns

  1. Service Container Integration Bind hydrators in AppServiceProvider:

    public function register() {
        $this->app->singleton(ClassMethodsHydrator::class, function () {
            return new ClassMethodsHydrator();
        });
    }
    
  2. Form Request Validation + Hydration

    public function update(Request $request, User $user) {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'age'  => 'sometimes|integer',
        ]);
        $hydrator = app(ClassMethodsHydrator::class);
        $hydrator->hydrate($validated, $user);
        $user->save();
    }
    
  3. API Resource Transformation Use HydratingIterator for collections:

    $users = User::all();
    $hydrator = app(ClassMethodsHydrator::class);
    $iterator = new \Laminas\Hydrator\Iterator\HydratingIterator($users, $hydrator);
    return response()->json(iterator_to_array($iterator));
    
  4. Custom Strategies Extend StrategyInterface for domain-specific logic:

    class DateStrategy implements \Laminas\Hydrator\Strategy\StrategyInterface {
        public function hydrate($value, ?array $data = null) {
            return \Carbon\Carbon::parse($value);
        }
        public function extract($value, ?object $object = null) {
            return $value?->format('Y-m-d');
        }
    }
    $hydrator->addStrategy('birthdate', new DateStrategy());
    

Gotchas and Tips

Pitfalls

  1. Deprecated Class Names (v3 Migration)

    • Old names (e.g., ClassMethods) are aliases but will be removed in v4.
    • Fix: Update to new names (ClassMethodsHydrator) and check HydratorPluginManager aliases.
  2. Strict Typing in v3

    • Methods now enforce type hints (e.g., hydrate(array $data, object $object)).
    • Fix: Ensure objects passed to hydrate() are instances of stdClass or custom classes.
  3. Naming Strategy Conflicts

    • Overlapping strategies (e.g., UnderscoreNamingStrategy + custom NamingStrategy) may cause unexpected property names.
    • Fix: Use CompositeNamingStrategy with explicit priority:
      $composite = new \Laminas\Hydrator\NamingStrategy\CompositeNamingStrategy([
          new \Laminas\Hydrator\NamingStrategy\UnderscoreNamingStrategy(),
          new CustomNamingStrategy(),
      ], new \Laminas\Hydrator\NamingStrategy\PassthroughNamingStrategy());
      
  4. Circular References

    • Hydrating nested objects with bidirectional relationships (e.g., UserPost) causes infinite loops.
    • Fix: Use AggregateHydrator with HydratorListener to track hydration state:
      $listener = new class implements \Laminas\Hydrator\Aggregate\HydratorListener {
          private $hydratedObjects = [];
          public function onHydrate(\Laminas\Hydrator\Aggregate\HydrateEvent $event) {
              $this->hydratedObjects[$event->getHydratedObject()->id] = true;
              return $event->getHydratedObject();
          }
      };
      $hydrator->addListener($listener);
      
  5. Filter Order Matters

    • Filters are evaluated in registration order (first match wins).
    • Fix: Use FilterComposite for complex conditions:
      $filter = new \Laminas\Hydrator\Filter\FilterComposite([
          new \Laminas\Hydrator\Filter\MethodMatchFilter('isPublic'),
          new \Laminas\Hydrator\Filter\NumberOfParameterFilter(0),
      ], \Laminas\Hydrator\Filter\FilterComposite::CONDITION_AND);
      

Debugging Tips

  1. Inspect Extracted Data Override extract() to log intermediate steps:

    $hydrator->setExtractCallback(function ($property, $value, $object) {
        logger()->debug("Extracting $property: " . print_r($value, true));
        return $value;
    });
    
  2. Validate Hydration Use HydratorAwareInterface to validate objects post-hydration:

    $hydrator->setHydrateCallback(function ($property, $value, $object) {
        if ($property === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException("Invalid email");
        }
        return $value;
    });
    
  3. Check for Missing Methods Enable methodExistsCheck in ClassMethodsHydrator to fail fast:

    $hydrator = new ClassMethodsHydrator(true, true); // Throws if setter/getter missing
    

Extension Points

  1. Custom Hydrators Extend AbstractHydrator for reusable logic:

    class ApiHydrator extends \Laminas\Hydrator\AbstractHydrator {
        public function hydrate(array $data, object $object) {
            foreach ($data as $key => $value) {
                $method = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
                if (method_exists($object, $method)) {
                    $object->$method($value);
                }
            }
            return $object;
        }
    }
    
  2. Dynamic Strategy Injection

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata