Hydrator - nullable collection strategy

CollectionStrategy requires that value being extracted is array or throws exception. What’s the best approach to allow nullable field? I have extended CollectionStartegy and return null when the value is null but maybe there is a better way of doing this?

Hello and welcome to our forums! :smiley:

You can combine different strategies. The following example is based on the documentation of laminas-hydrator:

$hydrator = new Laminas\Hydrator\ReflectionHydrator();
    new Laminas\Hydrator\Strategy\StrategyChain(
            new Laminas\Hydrator\Strategy\CollectionStrategy(
                new Laminas\Hydrator\ReflectionHydrator(),
            new Laminas\Hydrator\Strategy\ClosureStrategy(
                static function ($value) {
                    return $value ?? [];

This is a kind of solution, but not entirely. I can see that StrategyChain processes the values in LIFO order, which converts null to an array and then passes an empty array to CollectionStrategy. The result is an array, not null. This could work if there was class NullStrategy implements BreakStrategyInterface and StrategyChain would contain

 * {@inheritDoc}
public function extract($value, ?object $object = null)
    foreach ($this->extractionStrategies as $strategy) {
        $value = $strategy->extract($value, $object);

        if ($strategy instanceof BreakStrategyInterface) {

    return $value;

I’m not sure if it’s not a bug or at least incomplete functionality. DateTimeFormatterStrategy, ExplodeStrategy and HydratorStrategy - all have support for null values.

It’s a new feature and you are invited to create a feature request. :smiley: