Factory patterns: Collaborators Map

DZone 's Guide to

Factory patterns: Collaborators Map

· Web Dev Zone ·
Free Resource

Dependency Injection Containers are often proposed as a quick way of writing creation and wiring code: instantation of classes, the connection of object collaborators and their reuse inside the object graph.

However, like for every library, you should first evaluate if the costs and benefit of integrating it are worth it. The alternative is to write your own factory classes, methods and closures: this article explains one of the patterns for building dynamic Factory objects, and as such lowers the cost of the second option. What you know how to do has a lower cost than what you still have to learn, considering risk and implementation time.

Why writing your own Factories?

I argue that the most natural solution, once you separate business logic and creation code, is to write the creation code on your own. We should ask instead why importing a library to borrow some of its power.

However, strictly speaking we can list some advantages of the Bring Your Own Code approach:

  • fewer external dependencies: your code can be reused in other projects without an hard dependency on a library like a Dependency Injection container.
  • Flexibility: every framework or library favores a number of use cases, making it more difficult to develop changes on other axes. This is true also for your code - no one can be closed against any modification - but at least in your code you decide which changes are easily supported, not the container's author.
  • Configuration is always performed via code instead of externalizing it in XML or strange array maps. A level of indirection has its costs too, and is a way of introducing parsing or logical errors that are more difficult to find with respect to a bug in PHP or Java code.

This isn't to say that in my opinion you should always use Factories over a DIC, especially as an application grows; but making a choice between Plain Old Code and library support is different than importing a DIC because it's the only way we know to build an object graph.

Today: Collaborators Map

This pattern supports the injection of a list of collaborators inside any object. The object graph is bipartite and composed of two levels:

  • The first level are the classes to instantiate.
  • The second level is the list of collaborators.

You request directly only objects of the first level to the Factory implementing Collaborators Map; the second level is only used inside them to share common responsibilities. For example, the first level may comprehend HTTP controllers and the second one Repositories that access the database. At the second level, objects may be heads of arbitrarily complex trees.

The key part of the Collaborators Map is that the collaborators from the Map are inject in the first level objects dynamically. Each object specifies a key of the map as collaborator:

class ForumController
    public function __construct(PostRepository $repository) { /* wiring... */ }

Then the only configuration needed is a map where keys are all the possible interfaces requested and values are the collaborators.

    'PostRepository' => new DoctrinePostRepository($entityManager)

The identification of the interface requested is performed with the type hint in my example, but it may be based on an annotation or on the variable name... Whatever you find useful (but robust). The type hint forces you to use an interface or abstract class name and introduces an automatic check on wiring; other keys are more flexible but less prone to discover wiring errors immediately, at creation time.

How it works

class CollaboratorsMapFactory
    public function __construct(array $collaborators)
        $this->collaborators = $collaborators;

     * @param  string $adapterClassName
     * @return object
    public function create($adapterClassName)
        $reflectionClass = new \ReflectionClass($adapterClassName);
        $constructor = $reflectionClass->getConstructor();
        if ($constructor !== NULL) {
            $arguments = $this->argumentsFor($constructor);
            return $reflectionClass->newInstanceArgs($arguments);
        } else {
            return $reflectionClass->newInstance();

    private function argumentsFor(\ReflectionFunctionAbstract $method)
        $collaborators = array();
        foreach ($method->getParameters() as $parameter) {
            $requiredInterface = $parameter->getClass()->getName();
            $collaborators[] = $this->collaborator($requiredInterface);

        return $collaborators;

    private function collaborator($role)
        if (!isset($this->collaborators[$role])) {
            throw new \RuntimeException("The role $role is missing.");
        $stored = $this->collaborators[$role];
        if ($stored instanceof $role) {
            return $stored;
        throw new \RuntimeException("The role $role is misconfigured.");

Easy extensions

Some modifications are easy to introduce: this form is built to allow them. For example:

  • Adding collaborators.
  • Adding new objects that use the same pool of collaborators.
  • Adding indirection over creation of collaborators, for example lazy-loading: instead of an object you could allow class names and closures by modifying the collaborator() method.
  • Adding custom collaborator creation: inside the closures above. The collaborator can be an edge node of a large graph of objects.
  • Adding different configurations for the same second-level class: again inside the closures above. Maps do not need to have unique values.

Hard extensions

The Open/Closed Principle can only be followed for some axes of change, not all of them. If these variations come up, an implementation of this pattern will suffer.

  • Adding different implementation of collaborators for the same interface, or in general map keys. You cannot do this, so I chose to incorporate map in the pattern name.
  • Adding different configurations for the same first-level class. The only configuration allowed is the injection of collaborators.

If you can think of other unexpected changes that challenge this pattern, please list them in the comments.


A pattern is a form for your code, a form you may or may not decide to adopt depending on the context your application offers. Be aware of what Collaborators Map can easily do and what calls for other creational patterns; use this reflection-based implementation as a template if you work with PHP.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}