Reputation: 93
I have a quick question. I am using the Zend Framework 1 and I am using a Data Mapper. Here is my code:
<?php
// application/model/Pos.php
class Application_Model_Pos extends Zend_Db_Table_Abstract
{
protected $_name = 'pos';
}
// application/model/MapperAbstract.php
abstract class Application_Model_MapperAbstract
{
private $_dbTable;
public function __construct(Zend_Db_Table_Abstract $dbTable)
{
$this->_dbTable = $dbTable;
}
public function findById($id)
{
$select = $this->_dbTable()->select()->where('id = ?', $id)->limit(1);
$row = $this->_dbTable()->fetchAll($select)->toArray();
if(!empty($row))
{
$this->_createEntity($row);
}
}
protected function _createEntity(array $row);
}
// application/model/PosMapper.php
class Application_Model_PosMapper extends Application_Model_MapperAbstract
{
public function __construct()
{
parent::__construct(new Application_Model_Pos());
}
protected function _createEntity(array $row)
{
return new Sb_Pos($row['name']);
}
// application/library/Sb/Pos.php
class Sb_Pos
{
public function __construct($name)
{
$this->_name = $name;
}
}
?>
With this code in your mind, where should I handle table dependencies? Should a mapper know about another mapper? Do I need a service layer?
Thanks for your help.
Upvotes: 2
Views: 296
Reputation: 1177
Hello and great question. I just recently did a presentation about this exact topic at MidwestPHP 2013 - the slides are here (ok - sorry about that self promotion!)
Basically, the short answer to your question is that I believe a service layer is required. When working with objects that have multiple ways to get populated and mapped, the service draws all the mappers together. Remember, the mapper can populate all or some of the data object... but it can't "jump" data sources. So, if your particular object requires multiple data sources to get its data, you'll have to pass that object from mapper to mapper.
An alternative - assuming you're just using a database in ZF here - would be to get the base db connection, ignoring your table data access object dependencies, and build a complex join to retrieve all the data. Some people would disagree with this - but its a very slippery slope: at what point to you start ignoring these separate tables and start combining your sql (for the sake of performance). Hope this helps!
Upvotes: 2