php mvc的实现
PHP MVC 实现方法
MVC(Model-View-Controller) 是一种设计模式,用于分离应用程序的业务逻辑、用户界面和用户输入。以下是 PHP 中实现 MVC 的基本方法。
目录结构
创建以下目录结构来组织代码:
app/controllers/存放控制器models/存放模型views/存放视图
public/存放入口文件和静态资源config/存放配置文件
模型(Model)
模型负责处理数据和业务逻辑。创建一个基础模型类,其他模型可以继承它。
// app/models/Model.php
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
}
// app/models/User.php
class User extends Model {
public function getUsers() {
$stmt = $this->db->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
视图(View)
视图负责显示数据。通常使用简单的 PHP 文件或模板引擎。
// app/views/users/index.php
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>Users</h1>
<ul>
<?php foreach ($users as $user): ?>
<li><?php echo $user['name']; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
控制器(Controller)
控制器处理用户请求,调用模型获取数据,并传递给视图。
// app/controllers/UserController.php
class UserController {
public function index() {
$userModel = new User();
$users = $userModel->getUsers();
require 'app/views/users/index.php';
}
}
路由
路由将 URL 映射到相应的控制器和方法。
// public/index.php
require '../app/controllers/UserController.php';
$action = $_GET['action'] ?? 'index';
$controller = $_GET['controller'] ?? 'user';
$controllerClass = ucfirst($controller) . 'Controller';
if (class_exists($controllerClass)) {
$controllerInstance = new $controllerClass();
if (method_exists($controllerInstance, $action)) {
$controllerInstance->$action();
} else {
echo "Action not found";
}
} else {
echo "Controller not found";
}
自动加载
使用自动加载来避免手动包含文件。

// public/index.php
spl_autoload_register(function ($class) {
$file = '../app/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
}
});
$action = $_GET['action'] ?? 'index';
$controller = $_GET['controller'] ?? 'user';
$controllerClass = 'controllers\\' . ucfirst($controller) . 'Controller';
if (class_exists($controllerClass)) {
$controllerInstance = new $controllerClass();
if (method_exists($controllerInstance, $action)) {
$controllerInstance->$action();
} else {
echo "Action not found";
}
} else {
echo "Controller not found";
}
使用框架
对于更复杂的应用,可以考虑使用现有的 PHP MVC 框架,如 Laravel、Symfony 或 CodeIgniter。这些框架提供了更多的功能和更好的结构。






