In a new post to my blog, I discuss about integrating Symfony Dependency Injection Service Container with Zend Framework. Dependency Injection is an Inversion of Control specific pattern highly used and encouraged throughout Zend Framework implementation. A Dependency Injection container manages your services life-cycle, it is in charge of their instantiation, configuration and injection as shared instances: no more need to use static methods, singletons or factories for your services!

Here's an example of what you could achieve after reading my series of posts:

  • Declare your services with a simple @Service annotation and configure their dependencies with @Inject annotation:
/**
 * @Service
 */
class Default_Service_MyService
{
    /**
     * @var Default_Service_myOtherService
     */
    protected $_myOtherService;

    /**
     * @param Default_Service_MyOtherService $myOtherService
     * @return Default_Service_MyService
     * @Inject
     */
    public function setMyOtherService($myOtherService)
    {
        $this->_myOtherService = $myOtherService;
        return $this;
    }

    public function myMethod()
    {
        // Do service layer stuff here
        // Eventually use injected myOtherService
        // ....
    }

    // ....
}
  • Then inject your services into your controllers:
class MyController extends Zend_Controller_Action
{
    /**
     * @Inject
     */
    private $_myService;

    public function indexAction()
    {
        $this->_myService->myMethod();
        // ....
    }
}

Enjoy!