Created
February 14, 2015 13:48
-
-
Save JSila/6be45aa4dd8c3279895a to your computer and use it in GitHub Desktop.
php reflection api 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 User { | |
protected $name; | |
public function __construct($name) | |
{ | |
$this->name = $name; | |
} | |
} | |
interface UserRepositoryInterface {} | |
class EloquentUserRepository implements UserRepositoryInterface { | |
protected $user; | |
public function __construct(User $user) | |
{ | |
$this->user = $user; | |
} | |
} | |
class UsersController { | |
protected $userRepository; | |
public function __construct(UserRepositoryInterface $userRepository) | |
{ | |
$this->userRepository = $userRepository; | |
} | |
} | |
class Container { | |
protected $bindings = []; | |
public function bind($interface, $implementation) | |
{ | |
$this->bindings[$interface] = $implementation; | |
} | |
public function resolve($className) | |
{ | |
$reflectionClass = new ReflectionClass($className); | |
$constructor = $reflectionClass->getConstructor(); | |
if (is_null($constructor)) return new $className; | |
$params = $constructor->getParameters(); | |
if (count($params) === 0) return new $className; | |
$newInstanceParams = []; | |
foreach ($params as $param) | |
{ | |
if ( ! is_null($param->getClass())) | |
{ | |
$dependency = $param->getClass(); | |
$dependencyName = $dependency->getName(); | |
if (isset($this->bindings[$dependencyName])) | |
{ | |
$dependencyName = $this->bindings[$dependencyName]; | |
if ( ! is_string($dependencyName)) // find out if binded value is closure | |
{ | |
return $reflectionClass->newInstance($dependencyName()); | |
} | |
} | |
$newInstanceParams[] = $this->resolve($dependencyName); | |
} | |
} | |
return $reflectionClass->newInstanceArgs($newInstanceParams); | |
} | |
} | |
$container = new Container; | |
$container->bind('UserRepositoryInterface', 'EloquentUserRepository'); | |
$container->bind('User', function() { | |
return new User('Jernej'); | |
}); | |
var_dump($container->resolve('UsersController')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment