Skip to content

Instantly share code, notes, and snippets.

@pete-otaqui
Created September 3, 2010 10:02
Show Gist options
  • Save pete-otaqui/563706 to your computer and use it in GitHub Desktop.
Save pete-otaqui/563706 to your computer and use it in GitHub Desktop.
vaguely realish code to demonstrate the dependency injection pattern
<?php
// this is the dependency injetion style stuff ...
class FlickrModel {
// first off, have some internal store for the object:
protected $_httpClient = null;
// have a method to get the object:
public function getHttpClient() {
if ( !$this->_httpClient ) {
$this->_httpClient = new HttpClient();
}
return $this->_httpClient;
}
// and a method to set it:
public function setHttpClient($client) {
$this->_httpClient = $client;
}
public function getSomeonesPictures($person) {
return $this->_httpClient("http://flickr.com/" . $person);
}
}
// here is the dependency we are setting up for injection
class HttpClient {
public function request($url) {
// this is crappy
return file_get_contents($url);
}
}
// this is an alternative that we want to inject
class MockHttpClient {
protected $_fixtures = array();
public function addFixture($url, $response) {
$this->_fixtures[$url] = $response;
}
public function request($url) {
if ( isset($this->_fixtures[$url]) ) {
return $this->_fixtures[$url];
} else {
throw new Exception("Called a url without a fixture");
}
}
}
// and in a test you could then do this:
class FlickrModelTest {
public function testFlickr() {
$fixture = "<html><body><img /></body></html>";
$fm = new FlickrModel();
$mockhttp = new MockHttpClient();
$mockhttp->addFixture("http://flickr.com/foo", $fixture);
// now let's inject the dependency!
$fm->setHttpClient($mockhttp);
$response = $fm->getSomeonesPictures("foo");
$this->assertEquals($fixture, $response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment