How can the separation of concerns between the Model and the database connection be maintained effectively in PHP MVC?
To maintain the separation of concerns between the Model and the database connection in PHP MVC, it is best to use a separate class or component for handling the database connection. This way, the Model can focus on business logic and data manipulation without being tightly coupled to the database implementation.
// Database connection class
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
private $connection;
public function __construct() {
$this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
}
// Model class
class User {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getUserById($id) {
$sql = "SELECT * FROM users WHERE id = $id";
$result = $this->db->query($sql);
return $result->fetch_assoc();
}
}
// Example of using the Model
$userModel = new User();
$user = $userModel->getUserById(1);
print_r($user);