Search code examples
design-patternsormdata-mapping

Should a Domain Object Contain Its Mapper?


Given a domain object (say, for example, Person), should that object contain its Data Mapper (Person_Mapper)?

For example, I could have an inactivate action work in these two different ways:

$mapper = new Person_Mapper();

$person = $mapper->load(1);

$person->active = false;
$mapper->save($person);

Or like this:

$mapper = new Person_Mapper();

$person = $mapper->load(1);

$person->inactivate();


class Person
{
    public function inactivate()
    {
            $this->active = false;
            $this->_mapper->save($this);
    }
}

Solution

  • The Person class should only know Person stuff, therefore shouldn't contain anything to do with data mapping.

    See http://en.wikipedia.org/wiki/Single_responsibility_principle