實(shí)現(xiàn)類(lèi):
代碼如下:
?
class Container
{
??? protected $setings = array();
?
??? public function set($abstract, $concrete = null)
??? {
??????? if ($concrete === null) {
??????????? $concrete = $abstract;
??????? }
?
??????? $this->setings[$abstract] = $concrete;
??? }
?
??? public function get($abstract, $parameters = array())
??? {
??????? if (!isset($this->setings[$abstract])) {
??????????? return null;
??????? }
?
??????? return $this->build($this->setings[$abstract], $parameters);
??? }
?
??? public function build($concrete, $parameters)
??? {
??????? if ($concrete instanceof Closure) {
??????????? return $concrete($this, $parameters);
??????? }
?
??????? $reflector = new ReflectionClass($concrete);
?
??????? if (!$reflector->isInstantiable()) {
??????????? throw new Exception("Class {$concrete} is not instantiable");
??????? }
?
??????? $constructor = $reflector->getConstructor();
?
??????? if (is_null($constructor)) {
??????????? return $reflector->newInstance();
??????? }
?
??????? $parameters = $constructor->getParameters();
??????? $dependencies = $this->getDependencies($parameters);
?
??????? return $reflector->newInstanceArgs($dependencies);
??? }
?
??? public function getDependencies($parameters)
??? {
??????? $dependencies = array();
??????? foreach ($parameters as $parameter) {
??????????? $dependency = $parameter->getClass();
??????????? if ($dependency === null) {
??????????????? if ($parameter->isDefaultValueAvailable()) {
??????????????????? $dependencies[] = $parameter->getDefaultValue();
??????????????? } else {
??????????????????? throw new Exception("Can not be resolve class dependency {$parameter->name}");
??????????????? }
??????????? } else {
??????????????? $dependencies[] = $this->get($dependency->name);
??????????? }
??????? }
?
??????? return $dependencies;
??? }
}
實(shí)現(xiàn)實(shí)例:
代碼如下:
?
require 'container.php';
?
?
interface MyInterface{}
class Foo implements MyInterface{}
class Bar implements MyInterface{}
class Baz
{
??? public function __construct(MyInterface $foo)
??? {
??????? $this->foo = $foo;
??? }
}
?
$container = new Container();
$container->set('Baz', 'Baz');
$container->set('MyInterface', 'Foo');
$baz = $container->get('Baz');
print_r($baz);
$container->set('MyInterface', 'Bar');
$baz = $container->get('Baz');
print_r($baz);
PHP怎么學(xué)習(xí)?PHP怎么入門(mén)?PHP在哪學(xué)?PHP怎么學(xué)才快?不用擔(dān)心,這里為大家提供了PHP速學(xué)教程(入門(mén)到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://m.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)