2

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_Abstract
{
    $_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.

moteutsch
  • 3,741
  • 3
  • 29
  • 35
  • that's the point where you notice that it's a lot tedious work to handcode a DataMapper and switch to an ORM, like Doctrine, that does this for you through configuration. – Gordon Nov 27 '10 at 17:35
  • 1
    I'd like to do it myself. But how DO I do it? – moteutsch Nov 27 '10 at 21:04
  • check out the [Object-Relational patterns](http://martinfowler.com/eaaCatalog/index.html) – Gordon Nov 27 '10 at 21:44

1 Answers1

2

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.

timdev
  • 61,857
  • 6
  • 82
  • 92
  • How would you go about setting up the `save` method in `Application_Model_PostMapper`? Presumably this needs to know about the `commentMapper` too - do you just use the one in the passed in `$post`? – ChrisA Sep 01 '11 at 16:12