Created
September 6, 2016 08:51
-
-
Save dcb9/d86bb2a942eb903a6105b832dc41feed to your computer and use it in GitHub Desktop.
Dependency Injection For Function 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 | |
/* | |
* # installation | |
* | |
* $ cat composer.json | |
* { | |
* "require": { | |
* "pimple/pimple": "~3.0" | |
* } | |
* } | |
* $ composer install | |
*/ | |
namespace Dcb9 { | |
interface SessionInterface { | |
public function getStorage(); | |
} | |
} | |
namespace { | |
require_once './vendor/autoload.php'; | |
use Pimple\Container; | |
class SessionStorage {} | |
class Session implements Dcb9\SessionInterface { | |
protected $storage; | |
public function __construct($storage) { | |
$this->storage = $storage; | |
} | |
public function getStorage() | |
{ | |
return $this->storage; | |
} | |
} | |
$container = new Container(); | |
$container['session_storage'] = function ($c) { | |
return new SessionStorage(); | |
}; | |
$container['session'] = function ($c) { | |
return new Session($c['session_storage']); | |
}; | |
$testFunc = function ($name, Dcb9\SessionInterface $session) { | |
var_dump($session); | |
var_dump($name); | |
}; | |
$refFunc = new ReflectionFunction($testFunc); | |
$args = []; | |
foreach ($refFunc->getParameters() as $param) { | |
$type = $param->getType(); | |
$value = null; | |
if ($type === null && $param->name == 'name') { | |
$value = 'bob'; | |
} else { | |
$className = $type->__toString(); | |
if($container['session'] instanceof $className) { | |
$value = $container['session']; | |
} | |
} | |
$args[$param->getPosition()] = $value; | |
} | |
$refFunc->invokeArgs($args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment