I am creating an application using Zend Framework and I want to use the data mapper design pattern for managing my database. What I don't understand is how to use the pattern with a relational database.
Suppose I have a table containing posts with columns id, title, text and author. I could use the following classes to manage this:
class Application_Model_DbTable_Posts extends Zend_Db_Table_Ab开发者_如何学Cstract
{
$_name = 'posts';
}
class Application_Model_PostMapper
{
public function setDbTable($dbTable);
public function getDbTable();
public function save($post);
public function find($id);
public function fetchAll();
}
class Application_Model_Post
{
protected $_id;
protected $_title;
protected $_text;
protected $_author;
public function __set($name, $value);
public function __get($name);
}
Now, suppose I wanted to create a one-to-many relationship -- comments, for example -- how would I do this? And a many-to-many relationship? -- or would that be done the same was as a one-to-many?
Please provide code samples in your answers if possible, in order to help me understand.
Generally speaking, if your Application_Model_Post models has a collection of Application_Model_Comments, you would set up appropriate Db_Table and Mapper for comments, and extend your Post model in some way, to enable getting comments for a particular post.
You might decide to inject the CommentMapper into your Post model:
class Application_Model_Post {
protected $_commentMapper;
function __construct($commentMapper){
$this->_commentMapper = $commentMapper;
}
function getComments(){
return $this->_commentMapper->findByPostId($this->getId());
}
}
Note that your Post model still knows nothing of the persistence layer. All the details about loading comments is abstracted away in your CommentMapper.
精彩评论