How can the principles of Object-Oriented Programming (OOP) be applied to restructuring PHP code, particularly in separating tasks into distinct classes with specific responsibilities?
To apply OOP principles to restructure PHP code, tasks can be separated into distinct classes with specific responsibilities. This can improve code organization, reusability, and maintainability by encapsulating related functionality within classes.
// Example of restructuring PHP code using OOP principles
class DatabaseConnection {
private $host;
private $username;
private $password;
private $database;
public function __construct($host, $username, $password, $database) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
public function connect() {
// Connect to the database using the provided credentials
}
public function query($sql) {
// Execute a SQL query on the connected database
}
public function close() {
// Close the database connection
}
}
class User {
private $db;
public function __construct(DatabaseConnection $db) {
$this->db = $db;
}
public function getUserById($id) {
// Retrieve user data from the database based on the provided ID
}
public function updateUser($id, $data) {
// Update user data in the database based on the provided ID and data
}
public function deleteUser($id) {
// Delete user data from the database based on the provided ID
}
}
// Implementation example
$db = new DatabaseConnection('localhost', 'root', 'password', 'my_database');
$user = new User($db);
$userData = $user->getUserById(1);
$user->updateUser(1, ['name' => 'John Doe']);
$user->deleteUser(1);