Created
May 29, 2018 18:10
-
-
Save cosmomathieu/0984b54f3d54825bc430b88f83c13b46 to your computer and use it in GitHub Desktop.
Playing around with PHP Dependency Injection
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 | |
/** | |
* In these examples: | |
* - The Controller needs a view renderer | |
* - The view renderer needs a Database and a Logger | |
* | |
* Note, that the interfaces aren't being defined here, just assume they're what you'd expect. | |
*/ | |
interface DatabaseInterface | |
{ | |
} | |
interface ControllerInterface | |
{ | |
} | |
interface ViewRendererInterface | |
{ | |
} | |
interface LoggerInterface | |
{ | |
} | |
class Database implements DatabaseInterface | |
{ | |
// Some stuff here that makes database stuff go. | |
} | |
class Logger implements LoggerInterface | |
{ | |
// Some stuff here that makes logging stuff go. | |
} | |
class ViewRenderer implements ViewRendererInterface | |
{ | |
protected $database; // Let's assume this needs a database as a property for something. | |
protected $logger; // Let's assume this needs a logger as a property for something. | |
public function __construct( | |
DatabaseInterface $db, | |
LoggerInterface $logger | |
) { | |
$this->database = $db; | |
$this->logger = $logger; | |
} | |
public function render() | |
{ | |
echo json_encode(['content' => []]); | |
} | |
} | |
class Controller implements ControllerInterface | |
{ | |
protected $viewRenderer; // Lets assume this needs the view renderer and nothing else, for whatever reason. | |
public function __construct(ViewRendererInterface $viewRenderer) | |
{ | |
$this->viewRenderer = $viewRenderer; | |
} | |
public function doStuff() | |
{ | |
$this->viewRenderer->render(); | |
} | |
} | |
class ProductionDependencyInjectionContainer | |
{ | |
public function getController() | |
{ | |
$viewRenderer = $this->getViewRenderer(); | |
return new Controller($viewRenderer); | |
} | |
public function getViewRenderer() | |
{ | |
$db = $this->getDatabase(); | |
$logger = $this->getLogger(); | |
return new ViewRenderer($db, $logger); | |
} | |
public function getDatabase() | |
{ | |
return new Database; | |
} | |
public function getLogger() | |
{ | |
return new Logger; | |
} | |
} | |
// And now, in the actual application code, we can instantitate the DI container, and get the controller, | |
// without caring at all about what the dependencies are or how they're handled. | |
$dic = new ProductionDependencyInjectionContainer; | |
$controller = $dic->getController(); | |
$controller->doStuff(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment