samedi 23 mai 2015

Understanding repository, persistance and data mappaing. Who does what?

Lately im trying to understand the repository pattern and how to map data from a database to a domain model. I'm working with the ZendFramework and trying to implement this pattern here.

In many examples and explanation you see examples for saving an entity like this:

class UserRepository 
{
     function add(User $user) {
          $this->db->save( $user );
     }
}

Or retrieving an object like this

class UserRepository 
{
     function findById($id) {
          return $this->db->fetchAll()->where('id = ' . $id);
     }
}

I assume that $this->db in a repository probably represents a tablegateway object whose job it is to bring data into the database or retrieve them. Correct?

And here is what i dont understand:

First: Why is the tablegateway given an object to save when it actually needs an array to push into the database? Should the tablegateway really be the one who gets the data from the object and save it in the database or has this to be prepared in the repository?

Second: When retrieving an object. Why is the return of the tablegateway right back to whoever needs the data?
Where is the mapping of the data out of the database (probably given as an array or objectrow) to the domain model taking place?

This doesnt make sense to me.

Maybe $this->db doesnt represent a tablegateway at all and i'm just understanding it all wrong.

Hope someone can help me to understand this :)

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire