Search code examples
phpoopdomain-driven-designfactories

What does a domain object factory look like?


I have a DataMapperFactory and I think I am doing it correctly and it makes sense to have one but I have a DomainObjectFactory too but it just seems pointless. This is it:

namespace libs\factories;
use models as Models;

class DomainObjectFactory {

    public function build($name) {

        $className = 'Models\\' . $name;

        return new className();

    }

}

The only advantage I can see of this is that I am keeping the new operator from being present all over my code.

There has to be more to a DomainObjectFactory than this right?

Any help would be great thanks.


Solution

  • In general, you can use the factory to abstract from specific implementations. If you use the new <classname> operator, you instantiate a specific class every time. If you want to interchange this class with another implementation at a later time, you will have to manually change every new statement.

    The factory pattern allows you to abstract from specific classes. A valid minimal use case might be something like this:

    interface UserInterface {
        public function getName();
    }
    
    class UserImplementationA implements UserInterface {
        private $name;
        public function getName() { return $this->name; }
    }
    
    class UserImplementationB implements UserInterface {
        public function getName() { return "Fritz"; }
    }
    
    class UserFactory {
        public function createUser() {
            if (/* some condition */) return new UserImplementationA();
            else                      return new UserImplementationB();
        }
    }
    
    $f = new UserFactory();
    $u = $f->createUser();   // At this point, you don't really have to care 
                             // whether $u is an UserImplementationA or
                             // UserImplementationB, you can just treat it as
                             // an instance of UserInterface.
    

    One use case (of many) when this becomes extremely useful is when working with unit tests. In Test-Driven Development, you often replace dependencies of classes with mock objects (objects that implement a certain interface, but don't really do anything). Using the factory pattern, it is quite easy to transparently substitute specific classes with mock classes.