This article mainly introduces the DependencyInjection code example of PHP dependency inversion. This article only provides the implementation code. For more information, see
Implementation class:
The code is as follows:
<? 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-> isdefavaluvalueavailable ()){
$ 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:
The code is as follows:
<? Php
Require 'iner INER. 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 );