How can the concept of Inversion of Control be applied in PHP development to improve code organization and maintainability?

Inversion of Control can be applied in PHP development by using dependency injection to decouple components and allow for easier testing, maintenance, and code organization. By injecting dependencies into classes rather than hardcoding them, we can easily swap out implementations and improve the flexibility and maintainability of our code.

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    }

    public function query($sql) {
        return $this->connection->query($sql);
    }
}

class UserRepository {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        $result = $this->db->query("SELECT * FROM users WHERE id = $id");
        return $result->fetch();
    }
}

$db = new Database('localhost', 'root', '', 'my_database');
$userRepository = new UserRepository($db);

$user = $userRepository->getUserById(1);