How can dependency injection be implemented in PHP to pass database access objects to different classes and methods?
To implement dependency injection in PHP for passing database access objects to different classes and methods, you can create a database connection class that creates the database connection object. Then, inject this database connection object into the classes or methods that need to access the database.
// Database connection class
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
public function getConnection() {
return $this->connection;
}
}
// Example class using dependency injection
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUserById($id) {
$stmt = $this->db->getConnection()->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
return $stmt->fetch();
}
}
// Create a new database connection
$db = new Database('localhost', 'username', 'password', 'database');
// Create a new instance of UserRepository with the injected database connection
$userRepository = new UserRepository($db);
// Example usage
$user = $userRepository->getUserById(1);
Related Questions
- What precautions should be taken when working with numerical values in SQL queries in PHP?
- In the context of PHP, how can URL encoding impact the extraction of keywords from HTTP_REFERER URLs?
- In what scenarios is it advisable to use JavaScript for cosmetic improvements in PHP forms, such as real-time validation?