Dependency class TwitterAPIClient { protected $httpClient; public function __construct() { $this->httpClient = new SomeCurlWrapper(); } /* ... */ } $client = new TwitterApiClient;
Dependency class TwitterAPIClient { protected $httpClient; public function __construct() { $this->httpClient = new SomeCurlWrapper(); } /* ... */ } $client = new TwitterApiClient; This
Injection class TwitterAPIClient { protected $httpClient; public function __construct($httpClient) { $this->httpClient = $httpClient; } /* ... */ } $client = new TwitterApiClient(new SomeCurlWrapper); And
Injection public function __construct() { $this->httpClient = new SomeCurlWrapper(); } public function __construct($httpClient) { $this->httpClient = $httpClient; } VS
Setter injection Injection class TwitterAPIClient { protected $httpClient; public function __construct() {} public function setHttpClient($httpClient) { $this->httpClient = $httpClient; } /* ... */ } $client = new TwitterApiClient; $client->setHttpClient(new SomeCurlWrapper);
Interface injection 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);
What it does: Container • injects object dependencies • creates objects on demand • objects could be shared • (and sometimes other stuff, like tagging, XML/ JSON/YAML config etc. )