Created
April 3, 2017 18:48
-
-
Save chrisblackwell/09c5d25cdb7e1f88fb921f879127fe06 to your computer and use it in GitHub Desktop.
Dependency Injection Example
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
<?php | |
class App | |
{ | |
/** | |
* Application Registry | |
* | |
* @var array | |
*/ | |
protected $registry = []; | |
/** | |
* Magic method to set the property | |
* @param string $name | |
* @param callback $resolver | |
*/ | |
public function __set($name, $resolver) | |
{ | |
$this->registry[$name] = $resolver; | |
} | |
/** | |
* Magic method to return the registry property | |
* | |
* @param string $name | |
* @return callback | |
*/ | |
public function __get($name) | |
{ | |
return $this->registry[$name](); | |
} | |
} | |
class Invoice | |
{ | |
/** | |
* Sample method | |
* | |
* @return string | |
*/ | |
public function doSomething() | |
{ | |
return 'we did something'; | |
} | |
} | |
$app = new App; | |
$app->invoice = function() { | |
$inv = new Invoice; | |
return $inv; | |
}; | |
var_dump($app->invoice->doSomething()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment