views:

29

answers:

1

Hello everyone,

im trying to implement the Data Gateway / Domain Pattern. I understand the basics and its a fantastic pattern to separate domain logic from the persistent data layer. Now i have following requirement:

Lets say i have 2 domain-models: User(s) and Company(ies). When i wanna retrieve a user list with all users, i would do something like that:

$userGateway = new Model_UserGateway();

$users = $userGateway->fetchAll();

foreach ($users as $user) {...}

that works very fine, but now the tricky part: I wanna now have a List with all users and their corresponding company. I could iterate through the users and instance for each user the related company, but that... isnt my favourite solution. In the worst case i produce nested database queries. Another approach would be, that i fetch additional user data with the gateway and deal with them... i dont know :(

Whats the best praxis to get a user list with the company info?

thanks in advance

Michael M

A: 

Implement a method like fetchAllWithCompany in your Model_UserGateway. In this method you perform a database query that fetches the information from both tables. E.g.

SELECT * 
FROM user 
LEFT JOIN company ON user.id = company.user_id

and then you get all the information you want with:

$users = $userGateway->fetachAllWithCompany();

This is the way I would do it. As you said, creating a query for every user to get it the company is not good.

Edit:

Assuming that your User object has a getCompany method, you can do:

foreach($users as $user) {
    $company = $user->getCompany()
}

Of course getCompany should return a Company object.

Do you want to implement this to learn? Because a lot of frameworks support such kind of database abstraction, e.g. the Zend framework.

Felix Kling
Thank you for answer! The userGateway returns a Set of User-Objects, what would return the fetchAllWithCompany method?
michaelm
@michaelm: Also a set of User-Objects. And a user object should have a method `getCompany`.
Felix Kling
@felix: i assume that a "value"-object have to be instanced completely with all data? So i would have to fetch all company data in the user-gateway to instantiate the company model correctly within the user model, right? (if not, i could imagine, that there is a lazy loading model pattern :-))
michaelm