0

由于 DataMapper 应该用于对象和关系数据库之间的数据交换/传输,我会得到这样的用户

$user = $this->entityFactory->build('User');
$userMapper = $this->mapperFactory->build('User');

$user->setId(43);
$userMapper->fetch($user);

这很好用,因为我可以User在映射器之外创建对象并将其传入,但是当我获得对象的集合/列表时该怎么办?

首先在映射器之外创建空对象似乎并不正确,并且肯定会导致一些问题,那么最好的方法是什么?

谢谢。

4

1 回答 1

0

I don't know if this question is still in your mind, however let me give you an answer to this. In principle the first step is the same

$userCollection = $this->entityFactory->build('UserCollection');
$userCollectionMapper = $this->mapperFactory->build('UserCollection');
$user = $this->entityFactory->build('User');
$user->setId(43);
$userCollection->add($user);
$userCollectionMapper->fetch($userCollection);

So the userObject would function here as an searchObject for the collectionMapper (like teresko proposed in an older thread). Your CollectionMapper would retrieve the data from the database and i prefer to use something like

//returns new User object
$newUser = $userCollection->newUser();
//populate user object with DB entry
$userCollectionMapper->populate($newUser,$DBresponse);
//add to collection
$userCollection->add($newUser);

Of course there would be a loop before that looping through the found lines in the database and you would have to clear the list of user objects before adding the results. So this is the way i would deal with the problem. Hope it helps.

于 2013-08-14T13:59:44.060 回答