Wednesday, September 11, 2013

Using the ServiceManager as an Inversion of Control Container (Part 1)

Intro:

In Zend Framework 1, it was difficult to follow best practices when it came to writing testable code. Sure, you could make testable models, but once you need those models in a controller, what do you do? Zend Framework 2 makes it much easier. In this post, I'll cover the basics of injecting a model into a controller.

Motivation:

The main goal here is to be able to wire up and configure your application from the highest level possible. Constructor injection + inversion of control makes it easy to determine which classes are dependent on other classes, and swapping classes with mocks or stubs is a breeze.

Prerequisites:
Begin by creating a new Buildingmodule, with its directory structure, similar to creating the Album module in the Getting Started guide.

To create objects, first let's take a look at what we are trying to get away from.

    $building = new \Building\Model\Building();

This is bad. At least in a controller, or another model. No more new anything (except maybe Exceptions...), no more hard-coded class names. Dependencies don't belong at this level of the code. Zend Framework 2's ServiceManager allows you to programmatically configure your dependencies. You should already be at least vaguely familiar with higher level dependency configuration from the ZF2 Getting Started guide, as this is how the AlbumController is configured, though it does a lot of stuff behind the scenes.

    $sm = $this->getServiceLocator();
    $building  = $sm->get('Building');

This approach is better, but you still don't want to put this in the controller. You should avoid pulling in classes using the ServiceManager anywhere except factories. Put another way, in general, $sm->get() does not belong in a controller or model, but does belong in Module.php's factories array, which I'll demonstrate further down. A class full of objects created this way has a lot of "soft dependencies", which are difficult to document and keep track of. Instead, to 'inject' a dependency into a class, it should be a parameter in the construction. Let's start by creating the BuildingController with a Building model as a dependency, which we'll learn how to inject shortly. I usually store dependencies as instance variables during construction and access them when needed with 'getters'. In this example, we are still instantiating a new ViewModel from within the controller. We'll fix this in Part 2, where we learn how to use the ServiceManager to create objects with runtime dependencies (such as the $variables parameter in the ViewModel construction)

 
<?php
#module/Building/src/Building/Controller/BuildingController.php
namespace Building\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class BuildingController extends AbstractActionController
{
    protected $_building;

    public function __construct($building)
    {
        $this->_building = $building;
    }

    protected function _getBuilding()
    {
        return $this->_building;
    }
    protected function _getViewModel($variables=null)
    {
        #we'll fix this later
        return new \Zend\View\Model\ViewModel($variables);
    }
    public function indexAction()
    {
        $building = $this->_getBuilding();
        $building->addLayer('blue');
        $building->addLayer('red');
        $viewModel = $this->_getViewModel(array('building'=>$building));
        return $viewModel;
    }
}

The Application's ServiceManager is responsible for creating services (the model and controller are both services). Internally, when tasked with creating a service with a particular name, Building\Controller\Building for example, it runs canCreate("Building\Controller\Building"), which checks all of your aggregated config arrays. One of the places it checks by default is the array returned by the method getControllerConfig() in Module.php, if it exists. This is where we can add the factory closure for the model that the controller needs access to.

    #module/Building/Module.php excerpt
    public function getControllerConfig()
    {
        return array('factories' => array(
            'Building\Controller\Building' => function ($sm)
            {
                $building = $sm->getServiceLocator()->get('Building');
                $controller = new Controller\BuildingController(
                    $building, $viewFactory);
                return $controller;
            }
        ));
    }

Creating controllers is actually handled by the ControllerManager, a (sub)subclass of the main ServiceManager, and $usePeeringServiceManagers is set to false, which is why we need $sm->getServiceLocator()->get() here instead of just $sm->get(); it needs to retrieve the main ServiceManager to have access to the rest of the application's services.

In this controller, the constructor triggers the instantiation of the Building model. The model isn't actually created until the controller's constructor runs, since it is not a model being passed in, but a factory. The factory is a closure, a function without a name which can be saved as a variable. The ServiceManager sets services as 'shared' by default, meaning that the first time it is referenced, it calls the closure creating the object, and every time after that it simply returns the already instantiated object.

It is important to note that if the name of controller configuration (in this case Building\Controller\Building) is listed here, it cannot be defined somewhere else as well. For example, if it is in the $config['controllers']['invokables'] section in your module.config.php, the ServiceManager will try to 'invoke' it, that is, construct it with no arguments, and will fail. If you are following along with your code, check if this is the case now, and fix it if necessary. I'll wait.

Let's create the Building model as a simple class with no dependencies for now.

 
<?php
#module/Building/src/Building/Model/Building.php
namespace Building\Model;

class Building
{
    protected $_bricks=array();

    public function addLayer($color)
    {
        $bricks = array($color, $color, $color);
        $this->_bricks[] = $bricks;
    }

    public function getBricks()
    {
        return $this->_bricks;
    }

}

Because there are no dependencies or other required constructor arguments, we can define Building\Model\Building as an invokable in Module.php. The getServiceConfig() method is one of the aggregated configs that the ServiceManager checks to see which services it can create, and you should recognize it from the Getting Started guide.

 
    #module/Building/Module.php excerpt
    public function getServiceConfig()
    {
        return array(
            'invokables'=>array(
                'Building'=>'Building\Model\Building',
            ),
        );
    }


ZF2 provides multiple ways of doing a lot of things. It is possible, for example, to separate the configuration into multiple files, which might be advisable once your wiring starts getting complicated. The factories can be their own classes which implement 'FactoryInterface' instead of closures defined in the config array.

But, we are done for now. Control has now been inverted. We are injecting a dependency (Building) into a controller using the ServiceManager, and all of our wiring and configuration is in one place, Module.php.

If you want to test it out now and get something running, read the rest of this post. Otherwise, check out Part 2 to learn how to inject a dependency where each instance needs to be distinct and have its own configuration, e.g. using a $model->findAll() or similar.

You'll need to create a view

 
<?php
#module/Buidling/view/building/building/index.phtml
?>
<table >
<?php
foreach ($this->building->getBricks() as $key=>$layer)
{
    echo '<tr>';
    foreach ($layer as $brick)
    {
        echo '<td style="text-align:center; border:1px solid black;'.
            ' background-color:' . $brick . ';">';
        echo $brick;
        echo '</td>';
    }
    echo '</tr>';
}
?>
</table>

And then be sure to set up a route to /building so it is accessible.
 
<?php
#module/Building/config/module.config.php
return array(
    'router' => array(
        'routes' => array(
            'building' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/building[/:action]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Building\Controller\Building',
                        'action'     => 'index',
                    ),
                ),
            ),
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'building' => __DIR__ . '/../view',
        ),
    ),
);

Don't forget the getConfig() and getAutoloaderConfig() methods in your Module.php.

    
    #module/Building/Module.php excerpt
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

Finally, just go to http://localhost/building, and you should see a simple empty page with the layers we added.
Check out https://github.com/rwilson04/zf2-dependency-injection/tree/part1 for the code.

Here's the link to Part 2 again.

Comments are welcome.

3 comments:

  1. Nicely explained!
    Keep up the good work :)

    ReplyDelete
  2. Big thank you for this! It clarified me some things as I begin with ZF2.
    I'm running into part2 :)

    ReplyDelete