Created
November 7, 2016 21:42
-
-
Save feketegy/8087178f4cac082d0996e10dc6f6b4fc to your computer and use it in GitHub Desktop.
dependency injection
This file contains hidden or 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
// DB Interface | |
interface DBInterface { | |
public function query( $myQuery ); | |
} | |
// Database Dependency Class | |
class Database implements DBInterface | |
{ | |
public function query( $myQuery ) { | |
return $myQuery; | |
} | |
} | |
// Class using Database class | |
class someOtherClass { | |
private $_db; | |
public function __construct( DBInterface $db ) { | |
$this->_db = $db; | |
} | |
public function executeQuery( $myQuery ) { | |
// blah blah | |
$query = $this->_db->query( $myQuery ); | |
return 'executeQuery - ' .$query; | |
} | |
} | |
// Unit Test | |
class mockDatabase implements DBInterface { | |
public function query( $myQuery ) { | |
return 'mockQuery'; | |
} | |
} | |
class test_someOtherClass { | |
private $_someOtherClass; | |
public function __construct() { | |
$mockDB = new mockDatabase(); | |
$this->_someOtherClass = new someOtherClass( $mockDB ); | |
} | |
public function test_executeQuery() { | |
$retVal = $this->_someOtherClass->executeQuery('test'); | |
return ( $retVal === 'executeQuery - mockQuery' ) ? 'test passed' : 'test failed'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment