How to handle domain object creation "inside" collections

139 Views Asked by At

I'm new to MVCish structure, so go easy on me, please. I'm coding my own small MVCish "framework" for understanding purposes. Bit by bit, I intend to understand how all fits together the right way.

Relying heavily on How should a model be structured in MVC? by tereško and the fact that Domain Object != Domain Object Collection, I'm trying to figure out a way to handle Domain Object creation in bulks and their respective insertion in the Collection.

Oh his example, he passes a single ServiceFactory instance to both the controller and the view. This instance has a MapperFactory and a DomainObjectFactory injected on its constructor. There is no Collection Factory.

$serviceFactory = new ServiceFactory(
    new DataMapperFactory($dbhProvider),
    new DomainObjectFactory
);

/* 
 * Initialization of View 
 */
$class = '\\Application\\View\\' . $request->getResourceName();
$view = new $class($serviceFactory);
$view->setDefaultTemplateLocation(__DIR__ . '/templates');

/*
 * Initialization of Controller
 */
$class = '\\Application\\Controller\\' . $request->getResourceName();
$controller = new $class($serviceFactory, $view);

ServiceFactory.php would be something like

class ServiceFactory
{
    private $domObjFactory;
    private $mapperFactory;

    private $services = array();

    public function __construct(MapperFactory $mapperFactory, DomObjFactory $domObjFactory)
    {
        $this->mapperFactory = $mapperFactory;
        $this->domObjFactory = $domObjFactory;
    }

    public function create($name)
    {
        if ( array_key_exists($name, $this->services) === false )
        {
            $serviceName = '\Vendor\\'.$name.'Service';

            $this->services[$name] = new $serviceName($this->mapperFactory, $this->domObjFactory);
        }

        return $this->services[$name];
    }
}

As an example, let's say I have a Domain Object called Contract and I want my view to show them all in a list. It should probably tell the "model" something like $ContractService->fetchAll(), which would instantiate a collection and tell the mapper to populate it with all the contracts. Right?

Considering the collection should contain Domain Objects and a method like $ContractMapper->fetchAll($collection) should probably create a bunch of them, how to handle their creation!?

  • Should I have a dedicated Collection Factory also?
  • Should I create single Domain Objects with a method inside the Collection Object?
  • Should I create single Domain Objects with a method inside the Collection Mapper?
  • If so, should I inject the Domain Object Factory inside one of them? (This would probable require a ServiceFactory with a bunch more Factory dependencies being injected, which is bad, right?)

I believe this could be easily achieved in a poorly coded way, but I'm trying to find the most elegant and clean solution.

0

There are 0 best solutions below