Home  >  Article  >  Backend Development  >  What is the use of php dependency injection?

What is the use of php dependency injection?

(*-*)浩
(*-*)浩Original
2019-09-16 10:32:323482browse

Inversion of Control (Inversion of Control, abbreviated as IoC) is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. The most common method is called Dependency Injection (DI).

What is the use of php dependency injection?

Changing the implementation of the dependency interface through configuration is also the most basic and core function of dependency injection

Flexibly control the instance scope of dependency implementation, singleton, one per thread, one per request, etc.

Dependent parameters, dependent dependencies, etc. management

The code is more concise and the logic is clearer

Mock is convenient for testing (recommended learning: PHP programming from entry to proficiency)

In general, it is to centrally manage the dependencies between function blocks and classes in the application through a unified framework

A simple For an example of dependency injection

Please look at the following code:

<?php
class Container {
 private $s=array();
 function __set($k, $c) { $this->s[$k]=$c; }
 function __get($k) { return $this->s[$k]($this); }
}

With the container class, how can we manage the relationship between A and B? As for dependencies, let’s talk in code:

<?php
class A
{
  private $container;
  public function __construct(Container $container)
  {
    $this->container = $container;
  }
  public function doSomeThing()
  {
    //do something which needs class B
    $b = $this->container->getB();
    //to do
  }
}

Then inject class B into the container class:

$c = new Container();
$c->setB(new B());

You can also pass in an anonymous function so that class B will not be passed in It is instantiated immediately, but the instantiation work is completed only when it is actually called:

$c = new Container();
$c->setB(function (){
  return new B();
});

The above is the detailed content of What is the use of php dependency injection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn