Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for a "MappedFrom" annotation. #142

Conversation

jensdenies
Copy link
Contributor

Hey,

Sometimes the array of data doesn't exactly match the property name of the class i'd like to hydrate. This PR aims to solve this by adding a "MappedFrom" annotation which allows you to optionally define a custom key name.

Example:

$data = [
    'property_1' => 'test'
];

class Data {
    /**
     * @MappedFrom(name="property_1")
     */
    public string $property1;
}

$hydrator->hydrate($data, new Data());

I'd love to know what you think.

Thanks.

@Ocramius
Copy link
Owner

Hey @jensdenies!

Overall, I think this should be an added layer on top of pre-existing hydration.

The above can be implemented as (pseudo-code):

final class MyHydrator implements HydratorInterface
{
    private HydratorInterface $next;
    public function __construct(HydratorInterface $next)
    {
        $this->next = $next;
    }

    function hydrate(object $object, array $data) : object {
    {
        return $this->next->hydrate($object, \array_merge($data, ['property1' => $data['property_1']]));
    }

    function extract(object $object) : array {
    {
        $extracted = $this->next->extract($object);

        return \array_merge($extracted, ['property_1' => $extracted['property1']]);
    }
}

For the use-cases where this field name mismatch, the overhead is mostly negligible, and I endorse doing it that way, instead of adding more complexity to this already quite complex project.

Alternatively, writing a custom hydrator can yield very similar results, without the amount of added magic.

I'm therefore not keen to add this particular feature to the project, and prefer to keep the convention (property names === map keys) simple and straightforward for the foreseeable future.

@jensdenies
Copy link
Contributor Author

Alright, thanks @Ocramius for taking the time to reflect on this (pun intended). I will separate this out into some kind of decorator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants