Last active
August 29, 2015 14:14
-
-
Save moon0326/6421728c45a87a622ed4 to your computer and use it in GitHub Desktop.
Simple IoC Container
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 Container | |
{ | |
protected $index = array(); | |
public function make($abstract) | |
{ | |
if ($this->has($abstract)) { | |
return $this->resolve($this->index[$abstract]); | |
} else { | |
return $this->resolve($abstract); | |
} | |
} | |
protected function resolve($concret) | |
{ | |
$reflector = new ReflectionClass($concret); | |
$method = $reflector->getConstructor(); | |
// the class doesn't have a cosntructor | |
if (is_null($method)) { | |
return new $concret(); | |
} | |
$dependencies = $method->getParameters(); | |
$parameters = array(); | |
foreach ($dependencies as $dependency) { | |
$dependencyClass = $dependency->getClass(); | |
if (!$dependencyClass) { | |
continue; | |
} else { | |
$dependencyClass = $dependencyClass->name; | |
} | |
if ($this->has($dependencyClass)) { | |
$dependencyObject = $this->make($dependencyClass); | |
} else { | |
$dependencyObject = $this->resolve($dependencyClass); | |
} | |
array_push($parameters, $dependencyObject); | |
} | |
return $reflector->newInstanceArgs($parameters); | |
} | |
public function has($key) | |
{ | |
return array_key_exists($key, $this->index); | |
} | |
public function bind($abstract, $concret) | |
{ | |
if (!is_string($abstract) && !is_callable($concret)) { | |
throw new InvalidArgumentException("binding name must be a string or callable object."); | |
} | |
if ($this->has($abstract)) { | |
throw new InvalidArgumentException($abstract." is already binded."); | |
} | |
$this->index[$abstract] = $concret; | |
} | |
} | |
interface Flyable | |
{ | |
public function fly(); | |
} | |
class HummingBird implements Flyable | |
{ | |
public function fly() | |
{ | |
echo "I'm flying~~~"; | |
} | |
} | |
$container = new Container(); | |
$container->bind('Flyable', 'HummingBird'); | |
$bird = $container->make('Flyable'); | |
var_dump($bird); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment