Created
September 3, 2010 10:02
-
-
Save pete-otaqui/563706 to your computer and use it in GitHub Desktop.
vaguely realish code to demonstrate the dependency injection pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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