How can PHP classes be structured to avoid having overly specific methods like fetch() within a general connection class like db_connection?
Having overly specific methods like fetch() within a general connection class like db_connection violates the principle of separation of concerns and can lead to a bloated, inflexible class. To avoid this, consider restructuring the classes so that each class has a single responsibility and methods are focused on specific tasks. For example, create a separate class for handling database queries and results, where fetch() method can be moved.
class DBQuery {
protected $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function fetch($query) {
// Perform the fetch operation using the provided query
// Return the fetched data
}
}
class DBConnection {
protected $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function query($query) {
$dbQuery = new DBQuery($this->connection);
return $dbQuery->fetch($query);
}
}
// Example of using the classes
$dbConnection = new DBConnection('localhost', 'username', 'password', 'database');
$result = $dbConnection->query('SELECT * FROM table');
Related Questions
- What are the security risks associated with storing passwords directly in a database in PHP?
- In what situations should users seek assistance from the system provider rather than the PHP community for error resolution?
- What are the best practices for outputting time calculations in PHP scripts to ensure accurate results across different environments?