In the context of PHP development, what are the advantages of passing database objects as parameters to class constructors or using setter methods?
When working with PHP development, passing database objects as parameters to class constructors or using setter methods allows for better separation of concerns and improves code reusability. By injecting database objects into classes, you can easily switch between different database connections or mock database objects for testing purposes. This also helps in making your code more modular and maintainable.
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function getConnection() {
return $this->connection;
}
}
class User {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUsers() {
$connection = $this->db->getConnection();
// Perform database query to get users
}
}
// Usage
$database = new Database('localhost', 'username', 'password', 'database');
$user = new User($database);
$user->getUsers();