ObjectHydrator icon indicating copy to clipboard operation
ObjectHydrator copied to clipboard

Cast using expected type

Open Robertbaelde opened this issue 1 year ago • 2 comments

This is a breaking change, since the interface of the caster changes. So probably need to be queued for a major release.

In my casters I sometimes need the expected type. Eg: when casting a EventSauce Id It is cumbersome to pass the expected ID class to the caster when it is already typehinted in the constructor

final readonly class SomeCommand
{
    public function __construct(
        #[IdCaster(AuthorId::class)]
        public AuthorId $authorId,
    ) {}
}

The expected type is already known in the hydrator, so with this PR we can change the caster to:

final readonly class SomeCommand
{
    public function __construct(
        #[IdCaster]
        public AuthorId $authorId,
    ) {}
}

Or even register it is default caster, so we don't have to annotate our ID's anymore.

This is a breaking change, since the interface of the caster changes

Robertbaelde avatar Mar 31 '24 11:03 Robertbaelde

@Robertbaelde I am looking for similar functionality, wouldn't it be possible to do this without a breaking change if we created 2 new interfaces and deprecated the older ones (whilst still supporting them)?

axlon avatar Jul 05 '24 11:07 axlon

I quite like the potential solution outlined in #68. Rather than just giving the type as a string passing in the full context of the definition could allow all sorts of fun things.

public function cast(
    mixed $value, 
    ObjectMapper $hydrator, 
    ?PropertyHydrationDefinition $context = null,
): mixed

Would be nice to get some sort of solution in for value objects though. Whatever route is taken.

cooperaj avatar Jun 06 '25 10:06 cooperaj