search
HomeBackend DevelopmentPHP TutorialUnderstanding php dependency injection and inversion of control, php dependency injection inversion_PHP tutorial

Understand php dependency injection and inversion of control, php dependency injection inversion

To understand the two concepts of php dependency injection and inversion of control, you must understand the following issues :

DI——Dependency Injection

IoC——Inversion of Control

1. Who are the participants? ​

Answer: Generally there are three parties, one is an object; one is the container of IoC/DI; the other is the external resource of an object. Let me explain the nouns again. An object refers to any ordinary Java object; the IoC/DI container simply refers to a framework program used to implement IoC/DI functions; the external resources of the object refer to the object. Needed, but obtained from outside the object, are collectively referred to as resources, such as: other objects needed by the object, or file resources needed by the object, etc.

2. Dependence: Who depends on whom? Why are there dependencies?

Answer: An object depends on the IoC/DI container. Dependencies are inevitable. In a project, there are various relationships between various classes, and it is impossible for them all to be completely independent, which forms dependencies. Traditional development uses direct calls when using other classes, which will form strong coupling, which should be avoided. Dependency injection borrows containers to transfer dependent objects to achieve decoupling.

3. Injection: Who injects into whom? What exactly is injected?

Answer: Inject the external resources it needs into the object through the container

4. Inversion of control: Who controls whom? Control what? Why is it called reversal?

Answer: The container control object of IoC/DI mainly controls the creation of object instances. Reversal is relative to positive direction, so what counts as positive direction? Think about the application under normal circumstances. If you want to use C inside A, what would you do? Of course, the object of C is created directly, that is, the required external resource C is actively obtained in class A. This situation is called forward. So what is reverse? That is, class A no longer actively obtains C, but passively waits for the IoC/DI container to obtain an instance of C, and then injects it into class A in reverse.

5. Are dependency injection and inversion of control the same concept?

Answer: As can be seen from the above: dependency injection is described from the perspective of the application. Dependency injection can be described more fully: the application depends on the container to create and inject it Required external resources; while inversion of control is described from the perspective of the container, the description is complete: the container controls the application, and the container reversely injects the external resources required by the application into the application.

Let’s take a closer look at some implementation methods of dependency injection through examples:

1. Constructor injection

<&#63;php
class Book {
  private $db_conn;
 
  public function __construct($db_conn) {
    $this->db_conn = $db_conn;
  }
}

2. Setter injection

<&#63;php

 
class book{
   private $db;
   private $file;
   function setdb($db){
     $this->db=$db;
   }
   function setfile($file){
     $this->file=$file;
   }
}
class file{}
class db{}
...

class test{
   $book = new Book();
    $book->setdb(new db()); 
   $book->setfile(new file());
}
&#63;>

The code of the above two methods is very clear, but when we need to inject many dependencies, it means adding a lot of lines, which will be difficult to manage.

A better solution is to create a class as the container for all dependencies. In this class, you can store, create, obtain, and find the required dependencies

<&#63;php
class Ioc {
  protected $db_conn;
  public static function make_book() {
    $new_book = new Book();
    $new_book->set_db(self::$db_conn);
    //...
    //...
    //其他的依赖注入
    return $new_book;
  }
}

At this time, if you want to obtain a book instance, you only need to execute $newone = Ioc::makebook();

The above is a specific example of container. It is better not to write a specific dependency injection method. It is better to use registry registration and get acquisition.

<&#63;php
class Ioc {
/**
* @var 注册的依赖数组
*/
 
  protected static $registry = array();
 
  /**
  * 添加一个resolve到registry数组中
  * @param string $name 依赖标识
  * @param object $resolve 一个匿名函数用来创建实例
  * @return void
  */
  public static function register($name, Closure $resolve)
  {
   static::$registry[$name] = $resolve;
  }
 
  /**
   * 返回一个实例
   * @param string $name 依赖的标识
   * @return mixed
   */
  public static function resolve($name)
  {
    if ( static::registered($name) )
    {
     $name = static::$registry[$name];
     return $name();
    }
    throw new Exception('Nothing registered with that name, fool.');
  }
  /**
  * 查询某个依赖实例是否存在
  * @param string $name id
  * @return bool 
  */
  public static function registered($name)
  {
   return array_key_exists($name, static::$registry);
  }
}

You can now register and inject one through the following methods

<&#63;php
$book = Ioc::registry('book', function(){
$book = new Book;
$book->setdb('...');
$book->setprice('...');
return $book;
});
 
//注入依赖
$book = Ioc::resolve('book');
&#63;>

The above is the understanding of PHP dependency injection and inversion of control. I hope it will be helpful for everyone to learn PHP programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1125883.htmlTechArticleUnderstand php dependency injection and inversion of control, php dependency injection inversion To understand php dependency injection and inversion of control Two concepts, you must understand the following issues: DI——Dependency Inject...
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
Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.