zendframework/zend-hydrator
Zend Hydrator provides strategies and tools to extract data from objects and hydrate objects from arrays in PHP. Supports naming strategies, custom hydrators, and flexible configuration, useful for forms, APIs, and domain model mapping.
This package provides hydrators for converting between arrays and objects — crucial for data transfer (e.g., form input → domain objects, Doctrine entities → API responses). Despite being archived and last updated in 2019, it remains stable and compatible with modern Laravel via Composer (via zendframework/zend-hydrator or its successor laminas/laminas-hydrator). Start by installing it:
composer require laminas/laminas-hydrator
Use the built-in hydrators:
ArraySerializable: For classes implementing ArraySerializableClassMethods: getter/setter-based (default convention: getFoo()/setFoo())DelegateBased: Use custom extraction/dehydration callbacksObjectProperty: Direct property access (less common in Laravel models)Minimal example:
use Laminas\Hydrator\ClassMethods;
$hydrator = new ClassMethods();
$entity = new User(); // with getUserName(), setUserName()
$data = $hydrator->extract($entity); // ['user_name' => 'Jane']
$newEntity = $hydrator->hydrate($data, new User());
In Laravel, common use cases include:
// In a custom FormRequest or Service
$hydrator = new ClassMethods();
$user = $hydrator->hydrate($request->all(), new User());
$user->save();
ClassMethods(true) to use underscore-case names for array keys matching Laravel’s naming).$hydrator->addDelegate('posts', new ClassMethods());
$data = collect($hydrator->extract($entities))->map(...);
ClassMethods uses lowercase with underscores (e.g., first_name) by default. Set constructor flag true to preserve camelCase (new ClassMethods(true)). Ensure this matches your API/DB conventions.laminas/laminas-hydrator (Laminas Project fork) to avoid autoloader warnings. Update use Zend\... → use Laminas\....ClassMethods may miss attributes. Prefer ArraySerializable or custom hydrators for models.// In a Service Provider
$this->app->singleton(\Laminas\Hydrator\ClassMethods::class, fn () => new ClassMethods(true));
extract($object, []) or hydrate([], $object) to test hydrator behavior.ClassMethods to override naming strategies or add custom logic:
class AppClassMethods extends ClassMethods
{
protected function extractByName($object, $propertyName, $extraFields = [])
{
// Custom logic: e.g., camelCase-to-snake_case conversion
return parent::extractByName($object, $propertyName, $extraFields);
}
}
How can I help you explore Laravel packages today?