php实现mvc框架
理解MVC架构
MVC(Model-View-Controller)是一种设计模式,将应用程序分为三个核心组件:模型(Model)处理数据和业务逻辑,视图(View)负责展示数据,控制器(Controller)接收用户输入并协调模型和视图。
目录结构设计
典型的MVC框架目录结构如下:
app/
controllers/
models/
views/
public/
index.php
assets/
core/
Router.php
Database.php
Controller.php
Model.php
实现核心组件
路由(Router)
路由解析URL并调用对应的控制器和方法:
class Router {
public static function route($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)) {
call_user_func_array([$controller, $action], array_slice($urlParts, 2));
} else {
throw new Exception("Method $action not found");
}
} else {
throw new Exception("Controller $controllerName not found");
}
}
}
基础控制器
提供视图渲染和公共方法:
class Controller {
protected function render($view, $data = []) {
extract($data);
require_once "../app/views/$view.php";
}
}
基础模型
封装数据库操作:
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
}
入口文件配置
public/index.php 作为单一入口:
require_once '../core/Router.php';
$url = isset($_GET['url']) ? $_GET['url'] : '';
Router::route($url);
示例控制器实现
class UserController extends Controller {
public function index() {
$userModel = new UserModel();
$users = $userModel->getAllUsers();
$this->render('user/index', ['users' => $users]);
}
}
示例模型实现
class UserModel extends Model {
public function getAllUsers() {
$stmt = $this->db->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
视图文件示例
app/views/user/index.php:
<!DOCTYPE html>
<html>
<body>
<?php foreach ($users as $user): ?>
<p><?= htmlspecialchars($user['name']) ?></p>
<?php endforeach ?>
</body>
</html>
自动加载类
使用spl_autoload_register避免手动包含文件:
spl_autoload_register(function ($className) {
$paths = [
'../app/controllers/',
'../app/models/',
'../core/'
];
foreach ($paths as $path) {
$file = $path . $className . '.php';
if (file_exists($file)) {
require_once $file;
}
}
});
数据库配置分离
建议将数据库配置放在单独文件(如config/database.php):
return [
'host' => 'localhost',
'dbname' => 'test',
'username' => 'root',
'password' => ''
];
错误处理
添加基本错误处理机制:
set_exception_handler(function ($e) {
echo "Error: " . $e->getMessage();
});
扩展建议
- 添加中间件支持
- 实现依赖注入容器
- 增加模板引擎集成
- 添加RESTful路由支持
- 实现ORM功能
通过以上步骤可以构建一个基础的PHP MVC框架,实际项目中可根据需求进一步扩展功能。







