This article mainly introduces PHP dependency inversion (Dependency Injection) code examples. This article only provides implementation code. Friends in need can refer to
Implementation class:
<?php 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; } }
Implementation example:
<?php 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);
The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
About the development of PHP and jQuery registration module
About PHP
– Introduction to EasyUI DataGrid data storage method
The above is the detailed content of About Dependency Injection in PHP. For more information, please follow other related articles on the PHP Chinese website!