///The Zend Framework, Dependency Injection and Zend_Di

The Zend Framework, Dependency Injection and Zend_Di

Zend_Di

A while ago I wrote this neat little subclass of Zend_Loader to add a
midgen of Dependency Injection to the Zend Framework application I was
then building. After emailing the lists to propose it be fully adopted
into Zend_Loader some time ago, I realised someone had proposed a novel
new component called Zend_Di, and that small change was since accepted
by Federico into his DI buster. This is a quick overview with very
simple use cases – read the full proposal for even more gory details
about your object innards using DI…

http://framework.zend.com/wiki/display/ZFPROP/Zend_Di+-+Dependency+Injection+Container

But what is Dependency Injection (DI)? And why should you care?

Dependency Injection is both the ultimate bane and blessing in PHP
programming. If you’re an experienced object oriented programmer,
chances are you already know what the term means, and why it’s an
all-consuming obsession. If you don’t, then here’s an overview.

When you start mucking about with objects you eventually realise that
the best way to get objects working together towards a unified
objective, is through composition. In other words, objects use other
objects, which in turn can use others. You end up not with a
restrictive inheritance tree, but a pool of objects injected into each
other to build up an overall purpose. The problem of course is how to
inject one object into another!

We can identify a few methods:

1. Pass objects in via a constructor
2. Pass object in via a setter
3. Let some external object manage it

The first two are prevelant in the Zend Framework and for good reason –
it helps ensure source code can be maintained in a highly decoupled
state. Which make it easier to subclass the Zend Framework to death ;),
and modify it’s components before use.

The third is often confused with the Singleton and Registry design
patterns. In short, people sometimes think that banging all
dependencies into a Registry and then retrieving from within objects is
the only extent of dependency injection required. Now it’s quite true a
Registry goes a long way, but let’s remember the Registry has to get
into the object before you used it. FYI – you probably passed in
through a setter (perhaps as a Front Controller user parameter) or are
using the Registry class as a Singleton Registry (calling
Zend_Registry::get() statically for example). Basically, the object’s
dependency becomes the Registry… And let’s assume the Registry is
only useful for objects used very frequently by all Controllers. And
then let’s assume mocking objects from a static scope is less then
exciting…

A neat example I like to use is that of a Controller. Let’s say you
wanted to create a Controller Action which fires off an email to your
address. We can make a few simple assumptions:

1. Only a few Controller Actions need Email support
2. An instance of Zend_Email won’t be in a Registry
3. We’ll assume Zend_Mail’s transport was setup previously (via static calls on Zend_Mail)

Here’s the sample Controller (accessed from http://example.com/email/developer):

class EmailController extends Zend_Controller_Action
{

public function developerAction()
{
$mail = new Zend_Mail;
$mail->setBodyText(‘This is the text of the mail.’);
$mail->setFrom(‘somebody@example.com’, ‘Some Sender’);
$mail->addTo(‘somebody_else@example.com’, ‘Some Recipient’);
$mail->setSubject(‘TestSubject’);
$mail->send();
}

}

Small problem, how do we mock Zend_Mail?

It’s an increasingly common practice in the real world to apply
Test-Driven Development (or to a much lesser barely existing extent in
PHP, Behaviour-Driven Development (BDD) :-)),
before writing implementation code. Part of those practices is to
isolate the system under test (SUT), or in BDD parlance to identify the
behaviour being specified.

In our case, it’s simply that the Controller should send an email. Do
we need to actually send an email? Well, if you really want to test
Zend_Mail and don’t trust Simon Mundy… ;-). Otherwise we should either stub, or mock, Zend_Mail out of the system.

How about?

class EmailController extends Zend_Controller_Action
{

public function developerAction()
{
$mail = Zend_Di::create(‘Zend_Mail’);
$mail->setBodyText(‘This is the text of the mail.’);
$mail->setFrom(‘somebody@example.com’, ‘Some Sender’);
$mail->addTo(‘somebody_else@example.com’, ‘Some Recipient’);
$mail->setSubject(‘TestSubject’);
$mail->send();
}

}

Hey?! Where’s my Zend_Mail "new" keyword vanished?

The above is a viable use case for the new Zend_Di proposal. In short,
Zend_Di offers a level of indirection, whereby you use an external
system (Zend_Di) to create objects while your testing framework (or
PHPSpec) can access the same external system to implant a replacement
Mock Object when executing tests. In this simple case, it’s basically a
proxy to Zend_Loader::loadClass() and a little Reflection.

If you can bang Zend Framework ops into PHPUnit, it works there too. For now indulge a PHPSpec developer:

class DescribeEmailController extends PHPSpec_Context_Zend
{

public function itShouldSendEmailToDeveloperOnDeveloperAction()
{
$mockMail = PHPMock::mock(‘Zend_Mail’);
Zend_Di::replaceClass(‘Zend_Mail’, $mockMail);

$mockMail->shouldReceive(‘setBodyText’)->with(‘This is the text of the mail.’)->once()->ordered();
$mockMail->shouldReceive(‘setFrom’)->with(‘somebody@example.com’, ‘Some Sender’)->once()->ordered();
$mockMail->shouldReceive(‘addTo’)->with(‘somebody_else@example.com’, ‘Some Recipient’)->once()->ordered();
$mockMail->shouldReceive(‘setSubject’)->with(‘TestSubject’)->once()->ordered();
$mockMail->shouldReceive(‘send’)->withNoArgs()->once()->ordered();

$this->get(‘developer’);

$mockMail->verify();
}

}

We’re cutting it fine by omitting configuration of the email details,
but you get the point. To write a Controller test or spec, you really
need to isolate the Controller by mocking its dependencies to ensure
the Controller behaves as expected, and interacts with Zend_Mail as
expected. We already know ZF has unit tests for Zend_Mail.Now you could
take the route of functional or acceptance testing, but since that’s
for a different purpose (client req’s met?) it’s not that useful in a
TDD or BDD session when the View doesn’t even exist yet and this is not
a final Controller version ;-).

But that’s just Zend_Di with a little indirection. What about this?!

class FormatController extends Zend_Controller_Action
{

public function boldemphasisAction()
{
$text = $this->getRequest()->text;

$formatter = new Text_Bold(new Text_Emphasis($text));

$this->view->text = $formatter->toString();
}

}

Decorating some text with HTML/CSS is just a simple idea… But how to
mock this entire construct in a controller? Or even more relevant, how
to change the precise Text_* classes being used without editing the
code every time it needs modification?

Well…

./config/di/format/boldemphasis.php

return array(
‘Formatter’ => array(
‘class’ => ‘Text_Bold’,
‘arguments’ => array(
‘__construct’ => ‘Emphasis’
)
),
‘Emphasis’ => array(
‘class’ => ‘Text_Emphasis’
}
);

And back to our controller…

class FormatController extends Zend_Controller_Action
{

public function boldemphasisAction()
{
$config = new Zend_Config( require ‘/path/to/config/di/format/boldemphasis.php’ );
$di = new Zend_Di_Container($config);
$formatter = $di->loadClass(‘Formatter’)->newInstance();

$this->view->text = $formatter->toString();
}

}

Now if we ever intend boldemphasisAction() to perform a dozen other
formatting steps, we can just stick them into the DI config file
without editing the actual code in the controller. For a simple
example, the usefulness is limited – but in a more complex web of
objects you can see the benefit more clearly. Especially if using a
similar web of objects numerous times with few differences.

Besides this sudden burst of flexibility, how does it help in testing?
And indeed how do we ensure not to overuse it for testing (the trick
question plaguing Spring… ;-)).
Obviously I’ve introduced more dependencies into the Controller (i.e.
Zend_Config is directly instantiated). Secondly, how can we influence
the Zend_Di_Container to substitute mock objects for the real ones it
would normally intantiate?

The first is an easy:

Zend_Di::loadClass(‘Zend_Config’,
require ‘/path/to/config/di/format/boldemphasis.php’);

Which is really the only right answer for a simple use case. You see,
Zend_Di doesn’t get mocked. It’s a Dependency Injection container,
which we use as part of the overall testing platform. The only thing we
have to change, is the configuration it uses…so that it instantiates
Mock Objects or Stubs we create in our test cases (or spec) instead.
Perhaps using (in a test):

Zend_Di::replaceClass(‘Zend_Config’, $config);

Where $config is a modified configuration for Zend_Di
containing references to some Mock objects for the Text_* classes we
wish to substitute into the Controller.

As for overuse – DI works wonders in small measures. There will always
be a tipping point where the benefits of a DI container are outweighed
by convenience, a point usually close to where mocking an object
provides little real benefit. Personally, I think DI containers work
wonders for Controller development in a TDD or BDD environment, even
better with a good mocking framework available!

2010-05-25T22:34:53+00:00 February 7th, 2008|PHP|0 Comments

About the Author:

 

Leave A Comment