php 实现mvc
PHP 实现 MVC 架构的方法
MVC(Model-View-Controller)是一种常见的软件设计模式,用于分离业务逻辑、用户界面和用户输入。以下是 PHP 实现 MVC 架构的关键步骤:
目录结构
典型的 MVC 目录结构如下:
app/
controllers/
models/
views/
public/
index.php
入口文件
public/index.php 是应用入口,负责初始化路由和调度请求:
require_once '../app/bootstrap.php';
$router = new Router();
$router->dispatch($_SERVER['REQUEST_URI']);
路由类
路由类解析 URL 并调用对应的控制器和方法:
class Router {
public function dispatch($url) {
$urlParts = explode('/', trim($url, '/'));
$controllerName = isset($urlParts[0]) ? ucfirst($urlParts[0]) . 'Controller' : 'HomeController';
$action = isset($urlParts[1]) ? $urlParts[1] : 'index';
if (class_exists($controllerName)) {
$controller = new $controllerName();
if (method_exists($controller, $action)) {
$controller->$action();
} else {
throw new Exception("Method $action not found");
}
} else {
throw new Exception("Controller $controllerName not found");
}
}
}
控制器示例
控制器处理用户请求并协调模型和视图:
class UserController {
public function index() {
$userModel = new User();
$users = $userModel->getAll();
include '../app/views/user/index.php';
}
}
模型示例
模型处理数据逻辑和数据库交互:

class User {
private $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
public function getAll() {
$stmt = $this->db->query('SELECT * FROM users');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
视图示例
视图负责展示数据:
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>User List</h1>
<ul>
<?php foreach ($users as $user): ?>
<li><?php echo htmlspecialchars($user['name']); ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
自动加载
使用自动加载避免手动包含文件:
spl_autoload_register(function ($className) {
$file = '../app/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require_once $file;
}
});
配置管理
创建配置文件管理数据库等设置:

return [
'db' => [
'host' => 'localhost',
'name' => 'test',
'user' => 'username',
'pass' => 'password'
]
];
高级实现建议
依赖注入
使用依赖注入容器管理对象创建:
class Container {
private $instances = [];
public function get($key) {
if (!isset($this->instances[$key])) {
$this->instances[$key] = new $key();
}
return $this->instances[$key];
}
}
前端控制器
使用单一入口点处理所有请求:
$request = $_SERVER['REQUEST_URI'];
$router->dispatch($request);
模板引擎
集成 Twig 或 Blade 等模板引擎:
$loader = new \Twig\Loader\FilesystemLoader('../app/views');
$twig = new \Twig\Environment($loader);
echo $twig->render('index.twig', ['users' => $users]);
ORM 集成
使用 Eloquent 或 Doctrine 替代原生 SQL:
class User extends \Illuminate\Database\Eloquent\Model {
protected $table = 'users';
}
这种实现方式提供了清晰的关注点分离,使代码更易于维护和扩展。可以根据项目需求调整复杂度,从简单实现逐步过渡到使用框架级别的解决方案。






