What are the potential drawbacks of passing database resources between classes in PHP?
Passing database resources between classes in PHP can lead to tightly coupled code, making it harder to maintain and test. It can also result in potential resource leaks if the database connection is not properly closed. To solve this issue, it's better to encapsulate the database connection within a single class and use dependency injection to pass the database object to other classes that need it.
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
public function getConnection() {
return $this->connection;
}
}
class MyClass {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function someMethod() {
$stmt = $this->db->getConnection()->prepare("SELECT * FROM table");
$stmt->execute();
// Do something with the results
}
}
// Usage
$database = new Database();
$myClass = new MyClass($database);
$myClass->someMethod();
Keywords
Related Questions
- What are the potential risks of directly manipulating the $_POST array in PHP form data processing?
- What potential issues or errors can arise when attempting to upload files larger than 3 MB using PHP?
- What are the potential security risks associated with allowing users to input links in a PHP-based CMS?