Dependency Injection is a design pattern that allows us to inject dependencies into a class instead of creating them inside the class. This makes your code more flexible, easier to test, and maintain. Let's take a look at how it works in PHP with this example:
class User {
public $db;
// Constructor injection of Database dependency
public function __construct(Database $database) {
$this->db = $database;
}
public function checkConnection() {
return $this->db->connect();
}
}
interface Database {
public function connect();
}
class Mysql implements Database {
public function connect() {
echo "connect MySQL";
}
}
class Redis implements Database {
public function connect() {
echo "connect Redis";
}
}
$mysql = new Mysql();
$redis = new Redis();
// Injecting Redis as the dependency for User
$user = new User($redis);
$user->checkConnection(); // Output: connect RedisHow it works:
- User Class: The
Userclass depends on theDatabaseinterface to perform operations (like connecting to a database). But instead of creating a database connection directly inside theUserclass, we inject the dependency through the constructor. - Database Interface: The
Databaseinterface ensures that any class implementing it must have aconnect()method. - Mysql & Redis Classes: These are implementations of the
Databaseinterface. Both classes provide their own version of theconnect()method โ one for MySQL and one for Redis. - Injection: We inject an instance of either
MysqlorRedisinto theUserclass when creating theUserobject. In the example, we injectRedis. - Decoupling: The
Userclass doesn't need to know about the specifics of the database connection. It simply relies on theDatabaseinterface, making it easy to switch between different database implementations (MySQL, Redis, etc.) without modifying theUserclass.
Why use Dependency Injection?
- Flexibility: Easily swap out implementations without changing the dependent class.
- Testability: It's easier to mock dependencies in unit tests.
- Loose Coupling: Your classes are not tightly coupled to specific implementations, making the code more maintainable and scalable.
๐ก Tip: In real-world applications, Dependency Injection is commonly handled by a framework's service container, which manages object creation and dependency resolution.
#PHP # DependencyInjection #OOP #SoftwareDesign #PHP7 #CleanCode #ProgrammingTips