AgmLauncher
AgmLauncher

Reputation: 7270

Data Mapper pattern & Collection responsibility

I have a question about the Data Mapper pattern with respect to collections. I've been following this article on repositories, collections, and the data mapper pattern which I've found quite useful, but I need some clarification on something:

In those examples, the UserMapper takes a UserCollection in its constructor, meaning the UserMapper is actually responsible for taking the data it gets back from queries, and building a collection out of that data.

Doesn't this slightly violate SRP? Shouldn't the DataMapper just return a raw array from the query rather than ALSO build and return a collection wrapper for that data? Using code as an example, which of these is more appropriate?:

$userCollection = new UserCollection;
$userMapper = new UserMapper;

$userCollection->addUsers( $userMapper->fetchAll() ); // where addUsers() takes an array and does what it needs to

Vs

$userMapper = new UserMapper( new UserCollection );
$userCollection = $userMapper->fetchAll() // where fetchAll() queries the DB, then builds and returns a collection

The first one is a bit more cumbersome, but isn't it more loosely coupled?

Upvotes: 3

Views: 685

Answers (1)

Andrew
Andrew

Reputation: 12809

Collections are useful for all sorts of reasons, I will outline examples / uses;

1) What if you have 10000000 Users and you wish to find all?

If you generate an array containing all items you will very quickly run out of memory loading the full object graph for that many objects.

If you have a collection you can iterate over the whole set loading each one, one at a time. This is vastly better. Although there are times you may want an array of all items this is not the norm.

2) Hydrating Objects

You can have a collection which will Hydrate your objects as they are created. For example;

If you have a User object, but a User can have multiple addresses, email addresses, etc. You collection object can be part of the process of hydrating/populating the full graph of dependent objects when the main User object is created.

3) Proxy collections / Lazy Loading

You may have an Artist Object, which can have 10000000 Album's. If you load a few User objects, it would be inefficient to populate the Albums for each User too, but you can use a Collection as a proxy to lazy load them on demand for you.

There's many other uses for collections, but those alone are good enough reasons to use in the correct circumstance.

arrays are good and have their uses, so do collections. You can use them both when it's suitable to do so, and that's a decision you need to make when you design your application.

Upvotes: 2

Related Questions