php 实现mvc
PHP 实现 MVC 架构
MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的业务逻辑、用户界面和用户输入。以下是 PHP 实现 MVC 架构的关键步骤。
目录结构
创建以下目录结构以组织代码:
app/
controllers/
models/
views/
public/
index.php
入口文件 (index.php)
在 public/index.php 中处理所有请求并初始化 MVC 结构:
<?php
require_once '../app/bootstrap.php';
$router = new Router();
$router->dispatch();
路由类 (Router.php)
创建路由类解析 URL 并调用相应的控制器和方法:
class Router {
public function dispatch() {
$url = isset($_GET['url']) ? rtrim($_GET['url'], '/') : 'home';
$urlParts = explode('/', $url);
$controllerName = ucfirst($urlParts[0]) . 'Controller';
$methodName = isset($urlParts[1]) ? $urlParts[1] : 'index';
$controllerFile = '../app/controllers/' . $controllerName . '.php';
if (file_exists($controllerFile)) {
require_once $controllerFile;
$controller = new $controllerName();
if (method_exists($controller, $methodName)) {
$controller->$methodName();
} else {
die('Method does not exist');
}
} else {
die('Controller does not exist');
}
}
}
基础控制器 (Controller.php)
创建基础控制器类供其他控制器继承:

class Controller {
public function model($model) {
require_once '../app/models/' . $model . '.php';
return new $model();
}
public function view($view, $data = []) {
require_once '../app/views/' . $view . '.php';
}
}
示例控制器 (HomeController.php)
创建示例控制器处理特定页面请求:
class HomeController extends Controller {
public function index() {
$data = [
'title' => 'Home Page',
'content' => 'Welcome to our MVC framework'
];
$this->view('home/index', $data);
}
}
模型示例 (User.php)
创建模型处理数据逻辑:
class User {
private $db;
public function __construct() {
$this->db = new Database(); // 假设已实现数据库类
}
public function getUsers() {
return $this->db->query('SELECT * FROM users');
}
}
视图示例 (index.php)
创建视图文件显示数据:

<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $content; ?></h1>
</body>
</html>
数据库连接 (Database.php)
可选数据库连接类:
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
public function query($sql) {
return $this->connection->query($sql);
}
}
自动加载 (bootstrap.php)
实现自动加载以减少手动包含文件:
spl_autoload_register(function($className) {
$paths = [
'../app/controllers/',
'../app/models/',
'../app/core/'
];
foreach ($paths as $path) {
$file = $path . $className . '.php';
if (file_exists($file)) {
require_once $file;
}
}
});
配置 .htaccess
在 public/ 目录下创建 .htaccess 文件重写 URL:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
注意事项
- 确保服务器已启用 URL 重写
- 所有用户请求都应通过
public/index.php处理 - 模型应只包含数据逻辑,不涉及显示逻辑
- 视图应只负责显示,不包含业务逻辑
- 控制器协调模型和视图之间的交互
这种实现提供了基本的 MVC 结构,可以根据项目需求进一步扩展和完善。






