How to load child objects lazily with the Data Mapper pattern?
If I have a fairly complex User model that I would like to use the Data Mapping pattern to load, how would I lazily load some of the more intensive bits of user info without allowing the User to be aware of the UserMapper?
For example - if the User model allows for an array of Address objects (and th开发者_StackOverflow社区e User might have many of them, but not necessarily needed up front), how would I load those object if/when needed?
Do I make the User model aware of the AddressMapper?
Do I pass the User model BACK into the UserMapper which then hydrates only the Addresses?
Is there a better option?
Well, I have found the following clever pattern at one time, courtesy of Ben Scholzen, developer for the Zend Framework. It goes something like this:
class ModelRelation
implements IteratorAggregate
{
protected $_iterator;
protected $_mapper;
protected $_method;
protected $_arguments;
public function __construct( MapperAbstract $mapper, $method, array $arguments = array() )
{
$this->_mapper = $mapper;
$this->_method = $method;
$this->_arguments = $arguments;
}
public function getIterator()
{
if( $this->_iterator === null )
{
$this->_iterator = call_user_func_array( array( $this->_mapper, $this->_method ), $this->_arguments );
}
return $this->_iterator;
}
public function __call( $name, array $arguments )
{
return call_user_func_array( array( $this->getIterator(), $name ), $arguments );
}
}
Ben Scholzen's actual implementation is here.
The way you would use it, is something like this:
class UserMapper
extends MapperAbstract
{
protected $_addressMapper;
public function __construct( AddressMapper $addressMapper )
{
$this->_addressMapper = $addressMapper;
}
public function getUserById( $id )
{
$userData = $this->getUserDataSomehow();
$user = new User( $userData );
$user->addresses = new ModelRelation(
$this->_addressesMapper,
'getAddressesByUserId',
array( $id )
);
return $user;
}
}
class AddressMapper
extends MapperAbstract
{
public function getAddressesByUserId( $id )
{
$addressData = $this->getAddressDataSomehow();
$addresses = new SomeAddressIterator( $addressData );
return $addresses;
}
}
$user = $userMapper->getUserById( 3 );
foreach( $user->addresses as $address ) // calls getIterator() of ModelRelation
{
// whatever
}
The thing is though; this could get very slow, if the object graphs get very complex and deeply nested at some point, because the mappers all have to query their own data (presuming you are using a database for persistence). I experienced this when I used this pattern for a CMS to get nested Pages
objects (arbitrarily deep child Pages).
It could probably be tweaked with some caching mechanism, to speed things up considerably though.
精彩评论