This document provides an introduction to dependency injection containers (DIC). It begins by explaining dependency injection and its benefits over direct instantiation, such as easier testing and replacing dependencies. It then introduces the concept of a dependency injection container, which manages object instantiation and wiring of dependencies. Using a container allows configuring services differently for production versus development and avoids deeply nested instantiation code. The document demonstrates implementing a simple DI container and using it to resolve object graphs in place of direct construction.
6. Dependency
class TwitterAPIClient
{
protected $httpClient;
public function __construct()
{
$this->httpClient = new SomeCurlWrapper();
}
/* ... */
}
$client = new TwitterApiClient;
10. dependency.
class TwitterAPIClient
{
protected $httpClient;
public function __construct()
{
$this-httpClient = new SomeCurlWrapper();
}
/* ... */
}
$client = new TwitterApiClient;
20. Injection
class TwitterAPIClient
{
protected $httpClient;
public function __construct($httpClient)
{
$this-httpClient = $httpClient;
}
/* ... */
} And
26. Injection
public function __construct()
{
$this-httpClient = new SomeCurlWrapper();
}
VS
public function __construct($httpClient)
{
$this-httpClient = $httpClient;
}
45. Injection
Constructor injection
class TwitterAPIClient
{
protected $httpClient;
public function __construct($httpClient)
{
$this-httpClient = $httpClient;
}
/* ... */
}
$client = new TwitterApiClient(new SomeCurlWrapper);
46. Injection
Setter injection
class TwitterAPIClient
{
protected $httpClient;
public function __construct() {}
public function setHttpClient($httpClient) {
$this-httpClient = $httpClient;
}
/* ... */
}
$client = new TwitterApiClient;
$client-setHttpClient(new SomeCurlWrapper);
47. Injection
Interface injection
interface HttpClientInterface {
public function setHttpClient($httpClient);
}
class TwitterAPIClient implements HttpClientInterface {
protected $httpClient;
public function __construct() {}
public function setHttpClient($httpClient) {
$this-httpClient = $httpClient;
}
/* ... */
}
$client = new TwitterApiClient;
$client-setHttpClient(new SomeCurlWrapper);
97. Container
What it does:
• injects object dependencies
• creates objects on demand
• objects could be shared
• (and sometimes other stuff, like tagging, XML/
JSON/YAML config etc. )