What potential pitfalls or issues arise when combining user representation and database communication within the same class in PHP?
Potential pitfalls arise when combining user representation and database communication within the same class in PHP because it violates the Single Responsibility Principle and can lead to tightly coupled code that is difficult to maintain and test. To solve this issue, it is recommended to separate the concerns by creating separate classes for user representation and database communication.
// Separate class for user representation
class User {
private $id;
private $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
// Add getter and setter methods for properties
}
// Separate class for database communication
class UserDAO {
public function getUserById($id) {
// Database query to fetch user by ID
}
public function saveUser(User $user) {
// Database query to save user data
}
}
Related Questions
- What are some common methods for retaining user-selected options in dropdown lists when reloading a page in PHP?
- How can htmlentities be used in PHP to prevent special characters from interfering with the display of content in textareas?
- How can PHP developers ensure that input field values are successfully transmitted to specific elements on a target page within a frame setup?