什么是MVC模式?
MVC(Model-View-Controller)是一种软件设计模式,将应用程序分为三个核心组件:模型(数据处理)、视图(用户界面)和控制器(业务逻辑)。这种分离提高了代码的可维护性和可扩展性。
创建项目结构
/myapp /app /controllers - HomeController.php /models - User.php /views /home - index.php /core - Router.php - Controller.php - Model.php /public - index.php - .htaccess - config.php
实现核心组件
1. 路由系统 (Router.php)
<?php class Router { private $routes = []; public function addRoute($route, $controller, $action) { $this->routes[$route] = ['controller' => $controller, 'action' => $action]; } public function dispatch($uri) { if (array_key_exists($uri, $this->routes)) { $controller = $this->routes[$uri]['controller']; $action = $this->routes[$uri]['action']; $controllerFile = "app/controllers/" . $controller . ".php"; if (file_exists($controllerFile)) { require_once $controllerFile; $controllerClass = new $controller(); $controllerClass->$action(); } else { throw new Exception("控制器不存在: " . $controller); } } else { throw new Exception("路由未定义: " . $uri); } } } ?>
2. 基础控制器 (Controller.php)
<?php class Controller { public function model($model) { require_once 'app/models/' . $model . '.php'; return new $model(); } public function view($view, $data = []) { extract($data); require_once 'app/views/' . $view . '.php'; } } ?>
3. 基础模型 (Model.php)
<?php class Model { protected $db; public function __construct() { $this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } protected function query($sql, $params = []) { $stmt = $this->db->prepare($sql); $stmt->execute($params); return $stmt; } } ?>
创建示例应用
1. 首页控制器 (HomeController.php)
<?php require_once 'core/Controller.php'; class HomeController extends Controller { public function index() { $data = [ 'title' => '欢迎使用MVC框架', 'message' => '这是通过MVC模式渲染的页面' ]; $this->view('home/index', $data); } public function about() { $user = $this->model('User'); $users = $user->getAllUsers(); $data = [ 'title' => '关于我们', 'users' => $users ]; $this->view('home/about', $data); } } ?>
2. 用户模型 (User.php)
<?php require_once 'core/Model.php'; class User extends Model { public function getAllUsers() { $result = $this->query("SELECT id, name, email FROM users"); return $result->fetchAll(PDO::FETCH_ASSOC); } public function getUserById($id) { $result = $this->query("SELECT id, name, email FROM users WHERE id = ?", [$id]); return $result->fetch(PDO::FETCH_ASSOC); } } ?>
3. 视图文件 (index.php)
<!DOCTYPE html> <html> <head> <title><?php echo $title; ?></title> </head> <body> <h1><?php echo $title; ?></h1> <p><?php echo $message; ?></p> <a href="/about" rel="external nofollow" >关于我们</a> </body> </html>
4. 入口文件 (public/index.php)
<?php require_once '../core/Router.php'; // 初始化路由 $router = new Router(); // 添加路由规则 $router->addRoute('/', 'HomeController', 'index'); $router->addRoute('/about', 'HomeController', 'about'); // 获取请求URI并去除查询字符串 $requestUri = strtok($_SERVER['REQUEST_URI'], '?'); // 分发请求 try { $router->dispatch($requestUri); } catch (Exception $e) { echo "错误: " . $e->getMessage(); } ?>
5. URL重写配置 (public/.htaccess)
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [QSA,L]
框架使用示例
添加新功能
要添加新功能,只需遵循以下步骤:
- 在Router中添加新路由
- 创建对应的控制器和方法
- 如果需要数据操作,创建模型
- 创建视图文件展示内容
示例:添加用户详情页
// 在Router中添加路由 $router->addRoute('/user/{id}', 'UserController', 'show'); // 创建UserController class UserController extends Controller { public function show($id) { $userModel = $this->model('User'); $user = $userModel->getUserById($id); $this->view('user/show', ['user' => $user]); } } // 创建视图文件 app/views/user/show.php
框架优化建议
- 添加自动加载功能,避免大量require语句
- 实现中间件支持,用于处理认证、日志等
- 添加配置文件管理数据库连接等设置
- 实现ORM功能简化数据库操作
- 添加错误处理机制和日志记录
总结
通过本教程,您已经学会了如何从零开始构建一个简易的PHP MVC框架。虽然这个框架还很基础,但它包含了MVC模式的核心概念。您可以在此基础上继续扩展功能,打造更适合自己项目需求的框架。
理解MVC框架的工作原理对于PHP开发者至关重要,不仅能帮助您更好地使用主流框架(如Laravel、Symfony),还能提升您的系统设计能力和代码组织能力。