How can specialized database access objects be used in PHP classes to maintain reusability while adapting to different database structures?
Specialized database access objects can be used in PHP classes to maintain reusability by encapsulating database operations within these objects. By creating separate classes for database access, you can easily adapt to different database structures without affecting the rest of your codebase. This approach also promotes code organization and separation of concerns.
class UserDAO {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getUserById($id) {
// Database query to retrieve user by ID
}
public function updateUser($id, $data) {
// Database query to update user data
}
}
// Example of how to use the UserDAO class
$db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$userDAO = new UserDAO($db);
$user = $userDAO->getUserById(1);
$userDAO->updateUser(1, ['name' => 'John Doe']);
Related questions
-
PHP migration backward compatibility deprecated functions
-
PHP database update
-
MySQL pagination memory limit