Home >Backend Development >PHP Tutorial >Detailed explanation of dependency injection in php
This article talks about PHP's Dependency Injection. Students who don't know much about PHP dependency injection but are somewhat interested should read this article. No more nonsense. Let’s take a look at dependency injection in PHP directly!
is a method that allows us to decouple from hard-coded dependencies, so that at runtime or compile time SoftwareDesign Pattern that can be modified.
Simply put, dependency injection provides component dependencies through constructor injection, function calls or property settings.
A system achieves "Inversion of Control" by completely separating organizational control and objects. change". For dependency injection, this means achieving decoupling by controlling or instantiating dependent objects elsewhere in the system.
For example, the MVC framework usually provides super classes or basic Controller classes so that other controllers can obtain corresponding dependencies through inheritance
Because inheritance of the base class is optional, this method can completely remove dependencies and is not a dependency injection
The Dependency Inversion Principle is the "D" in the Object-Oriented Design Principle S.O.L.I.D. , advocates “relying on abstraction rather than concreteness”. To put it simply, the dependency should be an interface/convention or abstract class, rather than a specific implementation.
<?php namespace Database; class Database { protected $adapter; public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; } } interface AdapterInterface {} class MysqlAdapter implements AdapterInterface {}
Suppose you work on a team where a colleague is responsible for designing an adapter. In the first example, we need to wait until the adapter is designed before unit testing. Now since the dependency is an interface/convention, we can easily mock the interface test because we know that our colleagues will implement that adapter based on the contract
The code becomes more scalable. If we decide to migrate to a different database a year later, we only need to write an adapter that implements the corresponding interface and inject it. Since the adapter follows the convention of the interface, we do not need additional refactoring.
related suggestion:
Detailed explanation of the dependency injection process of PHP class reflection implementation
The above is the detailed content of Detailed explanation of dependency injection in php. For more information, please follow other related articles on the PHP Chinese website!