A Simple Resource Injector for ZF Action Controllers

Brandon Savage approached me
with an interesting issue regarding ZF bootstrap resources, and accessing
them in your action controllers. Basically, he'd like to see any resource
initialized by the bootstrap immediately available as simply a public member
of his action controller.

So, for instance, if you were using the "DB" resource in your application,
your controller could access it via $this->db.

I quickly drafted up a proof of concept for him using an action helper:

In this action helper, you would specify the specific resources you want
injected via the $_resources property - which would be values
you pass in. Each resource name would then be checked against those
available in the bootstrap, and, if found, injected into the action
controller as a property of the same name.

This makes it far more clear what your dependencies are, and also ensures
that each controller only gets the dependencies it plans on using. However,
I think it can still be improved: if the dependency is not found, we should
likely throw an exception!

This better satisfies the goals and needs of dependency tracking.
Dependencies are defined by the object that needs them, they're injected by
a collaborator, and missing dependencies results in an exception.

One potential improvement would be to allow specifying "default" resources
to inject into all controllers; this could be accomplished with a
constructor argument similar to the second example provided, and merging
that value with the controller dependencies. I'll leave that as an exercise
for the reader, though.

Action helpers are an area that is largely unexplored by many ZF users.
Hopefully this post will show just how powerful they can be, and how much
they can automate common tasks.