Detailed explanation of Ioc and Di examples in php
I have been using the ThinkPHP5 framework recently. After looking at its source code, I found that dependency injection (inversion of control) is also used in many places. I feel it is necessary to briefly talk with you about what dependency injection is and how to use it.
Let’s look at an example first:
<?php
class A
{
public $b;
public $c;
public function A()
{
//TODO
}
public function Method()
{
$this->b=new B();
$this->c=new C();
$this->b->Method();
$this->c->Method();
//TODO
}
}
class B
{
public function B()
{
//TODO
}
public function Method()
{
//TODO
echo 'b';
}
}
class C
{
public function C()
{
//TODO
}
public function Method()
{
//TODO
echo 'c';
}
}
$a=new A();
$a->Method();
?>
The above code, we can easily understand one sentence:
Class A depends on B Class and Class C
That is to say, if in the future development process, we need to modify Class B or Class C, once it involves renaming the function, changing the number of function parameters, or even adjusting the entire class structure, we will also have to modify it. Category A makes corresponding adjustments, and the independence of category A is lost. This is very inconvenient during the development process. This is what we call "one thing affects the whole body". If the two categories are written by two people separately, Conflicts often arise at this time. . .
If we really need to change categories B and C, is there any way to not change the code of category A or to change it as little as possible? Inversion of control is used here.
High-level modules should not depend on low-level modules, both should rely on abstractions.
Inversion of control (IOC) is an idea, and dependency injection (DI) is a method of implementing this idea.
The first method is called: constructor injection (this method is not recommended, but it is better than not using it)
class A
{
public $b;
public $c;
public function A($b,$c)
{
$this->b=$b;
$this->c=$c;
}
public function Method()
{
$this->b->Method();
$this->c->Method();
}
}
Client The class is written like this:
$a=new A(new B(),new C()); $a->Method();
The constructor of class A depends on class B and class C. It is passed in through the parameters of the constructor. At least one thing is achieved, which is B The creation of class object b and class C object c have been moved outside class A, so once class B and class C are changed, class A does not need to be modified, just change it in the client class.
If One day, we need to expand class B and make two subclasses of class B
class B
{
public function B()
{
//TODO
}
public function Method()
{
//TODO
echo 'b';
}
}
class B1 extends B
{
public function B1()
{
//TODO
}
public function Method()
{
echo 'b1';
}
}
class B2 extends B
{
public function B2()
{
//TODO
}
public function Method()
{
echo 'b2';
}
}
is also very simple. The client class is written like this:
$a=new A(new B2(),new C()); $a->Method();
So class A does not need to care about which subclasses class B has, as long as it is concerned about the client class.
The second method is called: factory mode injection (recommended)
class Factory
{
public function Factory()
{
//TODO
}
public function create($s)
{
switch($s)
{
case 'B':
{
return new B();
break;
}
case 'C':
{
return new C();
break;
}
default:
{
return null;
break;
}
}
}
}
Our Class A code is changed to:
class A
{
public $b;
public $c;
public function A()
{
//TODO
}
public function Method()
{
$f=new Factory();
$this->b=$f->create('B');
$this->c=$f->create('C');
$this->b->Method();
$this->c->Method();
//TODO
}
}
In fact, a small part has been decoupled. At least if the constructors of classes B and C change, such as modifying function parameters, etc., we only need to change the Factory class. That's it.
Abstraction should not depend on details, details should depend on abstraction.
Abstract the methods in classes B and C and make an interface
interface IMethod
{
public function Method();
}
In this way, the $b variable in class A The $c variable is no longer a concrete variable, but an abstract type variable. I don’t know how their Method is implemented until the moment it is run.
class B implements IMethod
{
public function B()
{
//TODO
}
public function Method()
{
//TODO
echo 'b';
}
}
class C implements IMethod
{
public function C()
{
//TODO
}
public function Method()
{
//TODO
echo 'c';
}
}
To summarize a few points:
1. We move the creation of class B objects and class C objects in class A to class A External
2. Originally, class A relied on class B and class C, but now it has become that A depends on Factory, and Factory depends on B and C.
Related recommendations:
Detailed example code explanation of PHP Inversion of Control (IOC) and Dependency Injection (DI)
Share practical tutorials on PHP Dependency Injection (DI) and Inversion of Control (IoC)
PHP Dependency Injection (DI) and Inversion of Control (IoC) )Example tutorial
The above is the detailed content of Detailed explanation of Ioc and Di examples in php. For more information, please follow other related articles on the PHP Chinese website!
PHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AMPHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
PHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AMPHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.
Why Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AMThe core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.
Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AMPHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.
The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AMPHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

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.







