Dependency injection (DI) is a design pattern that involves passing objects that a class depends on (its dependencies) as arguments to the class’s constructor or methods. This allows the class to be more loosely coupled and makes it easier to test and maintain.
In PHP, dependency injection is typically implemented using constructor injection, where dependencies are passed to the class’s constructor as arguments. Here is an example of a class that uses constructor injection:
class UserManager
{
private $database;
public function __construct(Database $database)
{
$this->database = $database;
}
public function createUser(string $name, string $email)
{
// use the injected database object to create a new user
$this->database->create('users', [
'name' => $name,
'email' => $email,
]);
}
}
In this example, the UserManager
class has a dependency on a Database
object, which is passed to the constructor as an argument. This allows the UserManager
class to use the Database
object to perform database operations, without having to create or manage the object itself.
To use this class, you would need to create an instance of the Database
class and pass it to the UserManager
constructor when creating an instance of the UserManager
class:
$database = new Database();
$userManager = new UserManager($database);
Using dependency injection in this way makes it easier to test the UserManager
class, because you can pass a mock or stub database object to the constructor instead of a real database, which allows you to control the behavior of the database and test different scenarios. It also makes it easier to change the implementation of the Database
class, because the UserManager
class does not have a hard dependency on the specific implementation of the Database
class.