Dependency Injection

Dependency injection is a design pattern in which an object receives other objects that it depends on.Dependency injection is a design pattern where an object receives its dependencies from external sources rather than creating them internally. This promotes loose coupling, easier testing, and greater flexibility in code maintenance. By injecting dependencies, developers can swap implementations more easily, making systems more modular and adaptable to change.

<?php

class MyObject {
    function __construct(private readonly Connection $database) {}

    function load(int $id): self {
        return $this->connection->select($id);
    }
}

?>

Documentation

See also Road to dependency injection, PHP-di and Dependency Injection in PHP: Laravel’s Magic vs. Symfony’s Explicitness.

Related : Autowiring, Clock, Dependency Injection Container, Injection, Interoperability