Method chaining for AbstractHydrator::addStrategy()

The return type of Laminas\Hydrator\AbstractHydrator::addStrategy() is void. This makes things more and more complicated, when you want to override this function to end up in a more fluent method chaining use case.

<?php
declare(strict_types=1);
namespace Application\Hydrator;

use Laminas\Hydrator\Strategy\StrategyInterface;
use Laminas\Hydrator\ClassMethodsHydrator as VendorClassMethodsHydrator;

class ClassMethodsHydrator extends VendorClassMethodsHydrator
{
    public function addStrategy(string $name, StrategyInterface $strategy): self
    {
        parent::addStrategy($name, $strategy);
        return $this;
    }
}

This always ends up in …

Fatal error : Declaration of Backend\Hydrator\ClassMethodsHydrator::addStrategy(string $name, Laminas\Hydrator\Strategy\StrategyInterface $strategy) must be compatible with Laminas\Hydrator\AbstractHydrator::addStrategy(string $name, Laminas\Hydrator\Strategy\StrategyInterface $strategy): void

Can we change the return type in the AbstractHydrator to self or better no return type? This would enable the following behaviour.

$hydrator = (new ClassMethodsHydrator())
    ->addStrategy('property_a', new DateTimeFormatterStrategy())
    ->addStrategy('property_b', new DateTimeFormatterStrategy())
    ->addStrategy('property_c', new DateTimeFormatterStrategy());

Hello and welcome to the forums! :smiley:

No return type is the wrong direction here. The goal is to define a clear interface. This enables a custom-fit implementation and usage.

Usually we use the fluent interface very rarely. This article offers some backgrounds: “Fluent Interfaces are Evil

Usually we use the fluent interface very rarely. This article offers some backgrounds: “Fluent Interfaces are Evil

Missed this one from Marco. Thank you for the good advice. This of course explains a lot.