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

What is the use of php dependency injection?

(*-*)浩
Release: 2023-02-24 06:48:02
Original
3594 people have browsed it

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); }
}
Copy after login

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
  }
}
Copy after login

Then inject class B into the container class:

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

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();
});
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template