How can the issue of passing database resources between classes be resolved using PHP best practices?
When passing database resources between classes in PHP, it is best practice to use Dependency Injection to inject the database connection into the classes that need it. This helps decouple the database connection from the classes, making the code more maintainable and testable.
// Database connection class
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 that requires database connection
class MyClass {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function fetchData() {
$connection = $this->db->getConnection();
// Code to fetch data from database using $connection
}
}
// Usage
$database = new Database('localhost', 'username', 'password', 'database');
$myClass = new MyClass($database);
$myClass->fetchData();
Related Questions
- What is the best practice for inserting session data directly into a database in PHP?
- What are the best practices for handling nested arrays in PHP, especially when extracting specific values like "dec_lat" and "dec_long"?
- What potential pitfalls should be considered when using regex in PHP for path extraction?