search
HomeBackend DevelopmentPHP ProblemHow to implement inversion of control in php

IoC, Inversion of Control, transfer of dependencies, dependence on abstraction rather than practice

DI, Dependency Injection , you don’t have to maintain the object’s dependencies in the code. The container automatically injects the dependencies into the specified object according to the configuration.

How to implement inversion of control in php

There are various stores in a certain area, and each store Stores sell four kinds of fruits: apples for ten yuan each, bananas for twenty yuan each, oranges for thirty yuan each, and watermelons for forty yuan each. Customers can purchase them at any store, and each store can provide total sales to the tax bureau at any time if needed. Forehead. (Recommended learning: PHP programming from entry to proficiency)

Initial code implementation

class Shop<br/>{<br/>    // 商店的名字<br/>    private $name;<br/><br/>    // 商店的总销售额<br/>    private $turnover = 0;<br/><br/>    public function __construct($name){<br/>        $this->name = $name;<br/>    }<br/><br/>    // 售卖商品<br/>    public function sell($commodity){<br/>        switch ($commodity){<br/>            case &#39;apple&#39;:<br/>                $this->turnover += 10;<br/>                echo "卖出一个苹果<br/>";<br/>                break;<br/>            case &#39;banana&#39;:<br/>                $this->turnover += 20;<br/>                echo "卖出一个香蕉<br/>";<br/>                break;<br/>            case &#39;orange&#39;:<br/>                $this->turnover += 30;<br/>                echo "卖出一个橘子<br/>";<br/>                break;<br/>            case &#39;watermelon&#39;:<br/>                $this->turnover += 40;<br/>                echo "卖出一个西瓜<br/>";<br/>                break;<br/>        }<br/>    }<br/>    // 显示商店目前的总销售额<br/>    public function getTurnover(){<br/>        echo $this->name.&#39;目前为止的销售额为:&#39;.$this->turnover;<br/>    }<br/>}<br/><br/>// 顾客类<br/>class Human<br/>{<br/>    //从商店购买商品<br/>    public function buy(Shop $shop,$commodity){<br/>        $shop->sell($commodity);<br/>    }<br/>}<br/><br/>// new一个名为kfc的商店<br/>$kfc = new Shop(&#39;kfc&#39;);<br/>// new一个名为mike的顾客<br/>$mike = new Human();<br/><br/>// mike从kfc买了一个苹果<br/>$mike->buy($kfc,&#39;apple&#39;);<br/>// mike从kfc买了一个香蕉<br/>$mike->buy($kfc,&#39;banana&#39;);<br/><br/>// 输出kfc的总营业额<br/>echo $kfc->getTurnover();<br/>

It can be seen that although the code is completed to meet the current needs implementation, but the shell() method at this time relies on specific practices and has absolute control. Once we need to add a new product to the store, such as mango, we have to modify the sell() method of the store class, which violates the OCP principle, which is open to extensions and closed to modifications.

At this point we can modify the code as follows

abstract class Fruit<br/>{<br/>    public $name;<br/>    public $price;<br/>}<br/>class Shop<br/>{<br/>    //商店的名字<br/>    private $name;<br/><br/>    //商店的总销售额<br/>    private $turnover = 0;<br/><br/>    public function __construct($name){<br/>        $this->name = $name;<br/>    }<br/><br/>    //售卖商品<br/>    public function sell(Fruit $commodity){<br/>        $this->turnover += $commodity->price;<br/>        echo &#39;卖出一个&#39;.$commodity->name.&#39;,收入&#39;.$commodity->price."元<br/>";<br/>    }<br/><br/>    //显示商店目前的总销售额<br/>    public function getTurnover(){<br/>        echo $this->name.&#39;目前为止的销售额为:&#39;.$this->turnover;<br/>    }<br/>}<br/><br/>//顾客类<br/>class Human<br/>{<br/>    //从商店购买商品<br/>    public function buy(Shop $shop,$commodity){<br/>        $shop->sell($commodity);<br/>    }<br/>}<br/><br/>class Apple extends Fruit<br/>{<br/>    public $name = &#39;apple&#39;;<br/>    public $price = 10;<br/>}<br/>class Bananae extends Fruit<br/>{<br/>    public $name = &#39;banana&#39;;<br/>    public $price = 20;<br/>}<br/>class Orange extends Fruit<br/>{<br/>    public $name = &#39;orange&#39;;<br/>    public $price = 30;<br/>}<br/>class Watermelon extends Fruit<br/>{<br/>    public $name = &#39;watermelon&#39;;<br/>    public $price = 40;<br/>}<br/><br/>//new一个名为kfc的商店<br/>$kfc = new Shop(&#39;kfc&#39;);<br/>//new一个名为mike的顾客<br/>$mike = new Human();<br/><br/>//mike从kfc买了一个苹果<br/>$mike->buy($kfc,new Apple());<br/>//mike从kfc买了一个香蕉<br/>$mike->buy($kfc,new Bananae());<br/><br/>//输出kfc的总营业额<br/>echo $kfc->getTurnover();<br/>

The above code adds an abstract class named Fruit, and all fruits are independently inherited from Fruit class. At this time, the sell() method no longer relies on the specific fruit name, but on the abstract Fruit class. The control right to determine how much to sell is no longer included in the method, but is passed in from outside the method. This is inversion of control, and the process of achieving inversion of control is dependency injection.

Through inversion of control, when an object is created, an external entity that controls all objects in the system passes the reference of the object it depends on to it. It can also be said that dependencies are injected into the object.

The above is the detailed content of How to implement inversion of control in php. 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use