Is it standard practice for public methods in PHP classes to directly execute queries or should they call private methods to handle query execution?
It is generally recommended to have public methods in PHP classes call private methods to handle query execution, rather than directly executing queries. This separation of concerns helps improve code maintainability, readability, and reusability. By delegating query execution to private methods, you can easily make changes to the database interaction logic without affecting the public interface of the class.
class DatabaseHandler {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function getUserById($userId) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userId);
return $this->executeQuery($query, $params);
}
private function executeQuery($query, $params) {
// Code to execute query using $this->connection
// Return query result
}
}
Related Questions
- What are the potential pitfalls of using the count() function in a MySQL query for updating multiple form fields in PHP?
- What are the potential pitfalls of trying to send emails locally using PHP's mail() function?
- Is there a way to subtract the output value from the total capacity of the disk to calculate free space in PHP?