PHP dependency inversion (Dependency injection) Code instance, dependency inversion principle _php Tutorial

Source: Internet
Author: User
Tags reflector xunit

PHP dependency inversion (Dependency injection) Code instance, dependency inversion principle


Implementation class:

Copy CodeThe 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->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 examples:

Copy the Code code as follows:
<?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);


Why is Dependency Injection

Dependency injection and control inversion are synonyms that have been merged. Control inversion (inversion of the English abbreviation for IOC) is an important object-oriented programming principle to reduce the coupling problem of computer programs. Control inversion There is also a name called Dependency injection (Dependency injection). Referred to as DI.
Origin
As early as 2004, Martin Fowler asked, "What controls have been reversed?" "This question. He concludes that the acquisition of dependent objects has been reversed. Based on this conclusion, he created a better name for the control reversal: Dependency Injection. Many extraordinary applications (more graceful and more complex than Helloworld.java) are two or more classes that implement business logic through each other's cooperation, which allows each object to have a reference to the object it is working with (that is, the object it depends on).   If this acquisition process is done on its own, as you can see, this will result in highly coupled code and difficult to test. The IoC is also known as the "dependency inversion Principle" ("Dependency inversion Principle"). Almost all frameworks use the "inverted injection (Fowler 2004) technique, which can be said to be an application of the IOC principle."   Smalltalk,c++, programmers of the object-oriented programming languages such as Java or various. NET languages have used these principles.   Control inversion is the core of the spring framework. Applying control inversion, when an object is created, it is passed to it by an external entity that regulates all objects within the system, and references the object to which it depends. It can also be said that the dependency is injected into the object. So, control reversal is a reversal of this responsibility about how an object obtains a reference to the object he relies on.
Edit this paragraph IOC is design mode
IOC is the IOC, not a technology, like Gof, is a design pattern. Interface driven Design interface driver, interface driver has many advantages, can provide different flexible sub-class implementation, increase code stability and robustness, etc., but the interface must be implemented, that is, the following statement will be executed sooner or later: ainterface a = new Ainterfaceimp ();   Thus, the coupling relationship arises, such as: Class a {ainterface A;   A () {} amethod () {a = new ainterfaceimp (); }} ClassA and Ainterfaceimp are dependencies, and if you want to use another implementation of ainterface, you need to change the code. Of course we can build a factory to generate the specific implementation of the desired ainterface based on the conditions, namely: interfaceimplfactory {ainterface Create (Object condition) {if (CO   Ndition = CondA) {return new Ainterfaceimpa ();   } elseif (condition = condb) {return new AINTERFACEIMPB ();   } else {return new ainterfaceimp (); }}} on the surface to some extent alleviate the above problems, but in essence this code coupling does not change.   This coupling can be completely solved through the IOC pattern, which removes the coupling from the code and puts it into a unified XML file, which is formed by a container when needed, that is, injecting the required interface implementation into the class that needs it, which may be the source of the "dependency injection" argument. IOC mode, by introducing IOC containers that implement IOC mode, can be used by IOC containers to manage the life cycle of objects, dependencies, etc., thus making the application configuration and ... Remaining full text >>

An interview question: You often on the technical website, c#net have what technical website and open source project?

Domestic Cnblog 51cto CSDN

Foreign
Www.asp.net
www.codeproject.com
Www.codeplex.com

As for open source projects, 51aspx could be

The famous NUnit, Json.NET, Log4net, Lucene.Net, Paint.NET, mono have gone to see the list below

1.[test] Xunit.net-one of the best test frameworks for TDD.
2.[test] rhinomocks Mocking framework-makes testing easier by creating a mock.
3.[test] White for automation of Windows applications-tested with code-driven Windows programs.
4.[test] Gallio Automation Platform-You can run many test frameworks, such as MSTest, XUnit, NUnit, and Mbunit.
5.[data] Fluent nhibernate-fluent NHibernate allows you to set the mapping relationship in C # code.
6.[oop] StructureMap Dependency injection/inversion of Control-decoupling classes and dependencies.
7.[oop] Managed Extensibility Framework-transition from static compiler to dynamic language program
8.[APPFX] S#arp architecture for Web applications-quickly develop Web applications with ASP. NET MVC and NHibernate.
9.[APPFX] Openrasta Rest based framework for building Web applications-let your program have a REST API interface.
10.[APPFX] csla.net application Framework-. NET Development Integrated Framework
11.[APPFX] spring.net Application Framework-web Development Integrated Framework
12.[runtime] Mono enables. NET on Linux and Mac-using. NET on Linux, BSD, and OS X.
13.[util] Sandcastle help File Builder-Create an MSDN-style document.
14.[helper] Easyhook for Windows API hooking-extend unmanaged code with managed code.
15.[helper] Json.NET for working with Json formatted data-serialized with a statement. NET object.
16.[helper] Excel Data Reader for Excel 2007-... Remaining full text >>

http://www.bkjia.com/PHPjc/892260.html www.bkjia.com true http://www.bkjia.com/PHPjc/892260.html techarticle PHP relies on inverted (Dependency injection) code instances, dependency inversion principle implementation class: Copy code code as follows: PHP class Container {protected $setings = array (); Public Fu Nction s ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.