Sau khi tìm hiểu về mvc. tổng kết từ nhiều trang và làm 1 demo nhỏ. Mọi người nhận xét giúp em em tổ chức code như thế này có ổn chưa và nó có đúng theo mô hình mvc chưa ạ. Em cám ơn
file index :
<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
require_once "library/database.php";
include_once "widgets/header.php";
?>
<?php
$controller = $_GET["c"] ?? "page";
$action = $_GET["a"] ?? "home";
include_once "routes.php";
?>
<?php include_once "widgets/footer.php"; ?>
file routes
<?php
$controllers = array(
"user" => ["show", "find"],
"page" => ["home", "error"]
);
if(array_key_exists($controller, $controllers)){
if(in_array($action, $controllers[$controller])){
call($controller, $action);
}
else {
call("page", "error");
}
}
else {
call("page", "error");
}
function call($controller, $action){
include_once "controller/" . ucfirst($controller) . "_Controller.php";
switch ($controller) {
case 'page':
$controller = new Page_Controller();
break;
case 'user':
include_once "model/User.php";
$controller = new User_Controller();
break;
}
$controller->{ $action }();
}
?>
file controller
<?php
class User_Controller {
public function show(){
$listUser = User::showAll();
include_once "view/user/show.php";
}
public function find(){
if(!isset($_GET["id"]))
call("page", "error");
$user = User::findUser($_GET["id"]);
include_once "view/user/find.php";
}
}
?>
file model
<?php
class User{
public $id;
public $username;
public $password;
public $email;
public function __construct($id, $username, $password, $email){
$this->id = $id;
$this->username = $username;
$this->password = $password;
$this->email = $email;
}
public static function showAll(){
$sql = "SELECT * FROM User";
$conn = Database::getConn();
$result = mysqli_query($conn, $sql);
$list = array();
while ($row = mysqli_fetch_assoc($result)) {
$user = new User($row["id"], $row["username"], $row["password"], $row["email"]);
array_push($list, $user);
}
return $list;
}
public static function findUser($id){
$id = (int)$id;
$sql = "SELECT * FROM User WHERE id=?";
$conn = Database::getConn();
$stmt = mysqli_prepare($conn, $sql);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
return mysqli_fetch_assoc($result);
}
else {
return false;
}
}
}
?>
file find.php trong view
<h1 style="color: green">FIND USER</h1>
<h3><?php echo $user["id"]; ?></h3>
<h3><?php echo $user["username"]; ?></h3>
<h3><?php echo $user["password"]; ?></h3>
<h3><?php echo $user["email"]; ?></h3>