pomm-project / ModelManager

Model Manager for the Pomm database framework.
MIT License
66 stars 27 forks source link

Add CollectionIterator::map #69

Closed tlode closed 4 years ago

tlode commented 7 years ago

Adds array_map helper for CollectionIterator

chanmix51 commented 7 years ago

Is it different from using a filter and then extract the iterator ?

$identity = function($row) { return $row; };
$result->registerFilter($identity)->extract();

Would that behave differently thant $result->map($identity); ?

tlode commented 7 years ago

Using a filter and the extract method would only return row values of type array. I would like to use map to easily transform rows or entities in something different, for example value objects.

$valueObjects = $result->map(
   function ($entity) { 
      return new SomeValueObject($entity->getProperty());
   }
);

I have such cases a lot and always have to iterate over the result set externally.

chanmix51 commented 7 years ago

Yes but this array is at the end used to hydrate entities by the iterator. This is the way we can turn json fields into embedded objects by example.

tlode commented 7 years ago

Perhaps, I don't understand the purpose of the filter feature. But I think, it is meant for a different use case.

In some cases I don't need to have flexible entities in the end. I wan't to transform the result set into something different, something independent.

Using array_map is a convenient way to achieve that and adding a map function in the CollectionIterator seemed appropriate.

It is another question if it could / should be rather added in the ResultIterator instead. I am not sure.

chanmix51 commented 7 years ago

That’s what I felt. If you do not need entities, wouldn’t that be a ConvertedResultIterator method instead ? (I am +1 on this)

tlode commented 7 years ago

No, I do all the queries through Model methods. ConvertedResultIterator wouldn't help, since CollectionIterator extends from ResultIterator.

chanmix51 commented 7 years ago

ConvertedResultIterator always return an array per row or can be expanded as an array of arrays. The CollectionIterator does the same but with entities. Would’t the CollectionIterator::map output something else than an array of entities in that case ?

tlode commented 7 years ago

Yes, as mentioned earlier it would return an array of anything you like. In my case simple value objects which I don't treat as entities

tlode commented 7 years ago

Sorry, I shall not write comments with the phone :-)

chanmix51 commented 7 years ago

Ok, the feeling I have regarding this is the following: add the map method in the ConvertedResultIterator maybe using a PHP generator. Break the inheritance withCollectionIterator (it was a bad idea) and use the interface developed in pomm-project/Foundation#71 instead. What do you think ?