Using the data card approach in the Zend Framework

Assume the following tables are installed for the Zend Framework application.

user (id) groups (id) groups_users (id, user_id, group_id, join_date) 

I applied the Data Mapper approach to models that basically give me:

  • Model_User , Model_UsersMapper , Model_DbTable_Users
  • Model_Group , Model_GroupsMapper , Model_DbTable_Groups
  • Model_GroupUser , Model_GroupsUsersMapper , Model_DbTable_GroupsUsers (to save relations that can be seen as creatures, pay attention to the join_date property)

I define _referenceMap in Model_DbTable_GroupsUsers:

 protected $_referenceMap = array ( 'User' => array ( 'columns' => array('user_id'), 'refTableClass' => 'Model_DbTable_Users', 'refColumns' => array('id') ), 'App' => array ( 'columns' => array('group_id'), 'refTableClass' => 'Model_DbTable_Groups', 'refColumns' => array('id') ) ); 

I'm having design issues:

1) Model_Group displays only the fields in the group table. How can I return a collection of groups of which the user is a member, as well as the date the user joined this group for each group? If I just added the property to the domain object, then I would have to report this to the group mapper, right?

2) Let's say I need to get the groups the user belongs to. Where should I put this logic? Model_UsersMapper or Model_GroupsUsersMapper ?

I also want to use the map binding mechanism (dependent tables) and probably use findManyToManyRowset or findDependentRowset, something like:

 $result = $this->getDbTable()->find($userId); $row = $result->current(); $groups = $row->findManyToManyRowset( 'Model_DbTable_Groups', 'Model_DbTable_GroupsUsers' ); 

This will create two queries when I could just write them in one query. I put this in the Model_GroupsUsersMapper class.

An improvement will be to add the getGroups method to the Model_User domain object, which lazily loads groups when necessary, by calling the appropriate method in the data converter, which requires a second question. Should I let a domain subject know about a data converter?

+4
source share
1 answer

This can be a rather confusing problem, since a relational database can be difficult to map to an object model.

First, I would like to focus on your requirements for the object model. For example, if in your object model the meaning of your user object is (almost) always to be in the know of groups, then this relationship should be included in the user class. If, on the other hand, you often need to use users without knowing which groups they are part of, you may have two user classes: the base class and the extended version of the group (base_user and group_user).

I would try to prevent the domain object from knowing about the data layer as such a form of the whole purpose of using this template. The data layer should pretty much be a dumb factory that creates your domain objects.

Just take it :)

+2
source

Source: https://habr.com/ru/post/1304913/


All Articles