In PHP development, what are the best practices for passing database objects to classes and methods for efficient and scalable code?
When passing database objects to classes and methods in PHP development, it is best practice to use Dependency Injection to decouple the database connection from the class itself. This allows for better scalability and testability of the code by making it easier to switch out different database connections or mock objects for testing.
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;
}
}
class User {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUsers() {
$query = "SELECT * FROM users";
$stmt = $this->db->getConnection()->query($query);
return $stmt->fetchAll();
}
}
// Usage
$database = new Database('localhost', 'root', 'password', 'mydatabase');
$user = new User($database);
$users = $user->getUsers();
Related Questions
- How can variables in a form field be inputted and sent to a MySQL database in PHP?
- In a business context, how can PHP scripts be optimized to handle emails for professional communication with clients?
- What steps can be taken to refactor the provided PHP code snippet to eliminate the use of eval() and improve code security and performance?