Skip to content

[ObjectMapper] Map a collection of objects #60615

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

Open
wants to merge 2 commits into
base: 7.4
Choose a base branch
from

Conversation

makomweb
Copy link

@makomweb makomweb commented Jun 1, 2025

Q A
Branch? 7.4
Bug fix? no
New feature? yes
Deprecations? no
Issues Fix #60518
License MIT

Add functionality to map multiple source objects to the specified target type.

This is my 1st PR to Symfony. Looking forward to all kinds of feedback.

@carsonbot carsonbot added this to the 7.4 milestone Jun 1, 2025
@makomweb makomweb changed the title [ObjectMapper] map a collection of objects [ObjectMapper] Map a collection of objects Jun 1, 2025
Copy link
Member

@alexandre-daubois alexandre-daubois left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because this is a new feature, don't forget to add a line in the changelog of the component! Also, don't forget to check fabbot which will provide some automated feedback on the code style.

}
}

if (!empty($exceptions)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We avoid using empty() in Symfony, this may be replaced by:

Suggested change
if (!empty($exceptions)) {
if ($exceptions) {

interface MapMultipleInterface
{
/**
* @template T of object
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this annotation be on the class instead of the method, so devs can use @implements MapMultipleInterface<Something>? I'm not sure this works well if the template definition is on the method

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alexandre-daubois I suggest to keep it consistent with the ObjectMapperInterface in the same package. The annotation is on the method there too. What do you think?


self::assertInstanceOf(D::class, $target[0]);
$firstTarget = $target[0];
assert($firstTarget instanceof D);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't use assert(), also the instance is already checked above with self::assertInstanceOf(D::class, $target[0]);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I only did this to support code completion of the IDE. Removed it.

Comment on lines 40 to 42
self::assertInstanceOf(D::class, $target[1]);
$secondTarget = $target[1];
assert($secondTarget instanceof D);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Comment on lines 43 to 44
self::assertEquals('foo2', $secondTarget->baz);
self::assertEquals('bar2', $secondTarget->bat);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We use self::assertSame wherever possible 🙂


self::fail('Mapping of second source element should have thrown!');
} catch (MapMultipleAggregateException $ex) {
self::assertEquals('Mapping source collection has failed.', $ex->getMessage());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self::assertEquals('Mapping source collection has failed.', $ex->getMessage());
self::assertSame('Mapping source collection has failed.', $ex->getMessage());

(Same for the occurrences below)

self::assertCount(1, $target, 'Mapping first source collection object should have passed!');
self::assertInstanceOf(D::class, $target[0]);
$firstTarget = $target[0];
assert($firstTarget instanceof D);
Copy link
Member

@alexandre-daubois alexandre-daubois Jun 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above, this isn't needed 🙂

@makomweb makomweb force-pushed the feat-60518/map-multiple-objects branch from c658ef1 to 467fce5 Compare June 22, 2025 10:13
@makomweb
Copy link
Author

makomweb commented Jun 22, 2025

@alexandre-daubois Thank you for your feedback.
I adjusted the code with your code review suggestions and rebased the branch of this PR.

@soyuka
Copy link
Contributor

soyuka commented Jun 30, 2025

Oh I missed this.

We could use #60442 for embedded collections, but I really don't understand the need for such a functionality inside the Mapper.

About naming instead of MapMultiple I'd suggest MapCollection but I'm again really not in favor of this.

interface MapCollectionInterface {
   public function map(iterable $sources) {}
}

What if your sources are of multiple types? What if you want to target different classes? What if you want to throw an exception after the first element fails to map?

I'm concerned that adding collection mapping to the new ObjectMapper component might not be the best path forward at this stage. In my opinion, it risks blurring the component's focus. One could argue this goes against the Single Responsibility Principle, as the component's core job is transforming a single object, not handling iteration logic. I also feel that a simple foreach loop is often a clearer and more explicit solution for developers. For now, I think it's preferable to encourage that approach, as it avoids adding underlying complexity to a component that would benefit from staying lean and focused while it's still experimental.

@makomweb
Copy link
Author

makomweb commented Jul 2, 2025

Thanks for your feedback @soyuka
I need to have a bit more clarity about what you mean. So please let's sort this step by step.

  1. When you write "inside the mapper" - you mean that the functionality from this MR is part of the Mapper bundle?
  2. About MapCollection - that's fine with me
  3. What if the source objects are of various types?
    This is where this approach plays it's strenghts:
  • it works like if individual objects are mapped and yield'ed
  • if a mapping of a discrete source object from the collection fails, this is collected in the aggregate exception and thrown at the and of the mapping process
  • successfull descrete mappings are yield'ed nonthless
  • this way it is up to the call side to decide how to proceed: are individual successfull mappings okay OR has the entire mapping of the collection failed
  1. To target different classes:
  • don't specify a target type
  • rely on the declared (annotated) mapping rule attached to the class of the source object
  1. What if "we want to fail early" and stop mapping the collection when the first mapping fails?
  • this is a good question imo
  • I can introduce a "fail early" flag which stops yielding immediately+
  1. Regarding your concerns in you final paragraph:
  • this seems to be a more fundamental question regarding implementing an ObjectMapper from scratch and not rely on existing bundles outside of Symfony, or am I missing something (e.g. a policy to do so)

Okay? I'd be happy to incorporate this.

@soyuka
Copy link
Contributor

soyuka commented Jul 2, 2025

I understand the strength of aggregating exceptions while yielding successful mappings. It’s a clever approach.

However, this is where I think the explicitness of a foreach loop is actually more powerful. A developer can easily replicate this exact behavior with a try-catch block inside a loop, giving them full, visible control over the process. This keeps the logic clear and in one place, rather than configured through one of the component's implementation.

You mentioned adding a fail-early flag, and this highlights my main concern. The fact that we immediately need options to control the iteration strategy suggests this feature is trying to solve too much. If we add a fail-early flag, what comes next? A flag for logging behavior? A flag for transactional mapping?

This is where I feel the feature starts to violate the Single Responsibility Principle. The ObjectMapper's job should be to map one object, while the calling code should be responsible for the iteration and error-handling strategy. By adding collection mapping, the component's responsibility expands, and its interface will likely become more complex to accommodate all these valid use cases. It also increases the maintenance burden of the component.

To me, the ObjectMapper component should excel at object-to-object transformation (e.g., a single DTO to a single Entity) nothing more.

A foreach loop is powerful, universally understood, and requires zero maintenance within the component itself. It gives developers the control they need without us having to build and maintain a complex API for all possible collection-handling scenarios.

@makomweb
Copy link
Author

makomweb commented Jul 3, 2025

@soyuka
I disagree with you. The implementation of the MapMultiple strongly uses single responsibility principle - it is decorating the ObjectMapper and that is how we prevail SRP, don't we?

I agree with you about the "fail-early" flag. What you write is the exact reason I did not introduce such a flag in the first place. And I am very much hesitant to introduce such a thing - it was just my suggestion to address the a concern you raised about with your "What if ..." questions in your 1st reply.

I also read many don'ts in your replies. Can you come up with a constructive comment please? Something like: The implemention here better fits into this place here ... or please make and adjustment there in order to improve this and that. That would be very helpful in order to bring this forward instead of blocking the process.

@soyuka
Copy link
Contributor

soyuka commented Jul 3, 2025

See what I wrote about the naming for something constructive.

I can't go into your direction as from the start of my work around this, I argue against collection mapping (or any other structure than an Object).

Indeed about the flag it was my suggestion, it's more to illustrate the maintenance burden behind handling traversables. It's really my opinion, maybe that the core team is fine adding such an option but I'm not. As the component creator I thought it was good to share this opinion :).

@makomweb
Copy link
Author

makomweb commented Jul 3, 2025

Now I have a better understanding of where your complaints are coming from and I can follow your reasoning to some degree.

To be very clear, my implementation is not to address an artificial problem. Instead it solves: #60518

For now, I am going to stop arguing with you about the pros and cons of this MR and kindly ask you to continue the discussion here. I am convinced this would be the better place because you can raise your concerns directly to the person who asked for a solution to mapping a collection of objects.

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.

[ObjectMapper] Add possibility to map multiple objects at once
4 participants