php简单实现 mvc
实现MVC架构的基本步骤
PHP实现MVC(Model-View-Controller)架构可以通过以下方式完成。MVC将应用程序分为三个主要部分:模型(数据处理)、视图(用户界面)和控制器(业务逻辑)。

目录结构
创建以下基本目录结构:

app/
controllers/
models/
views/
index.php
入口文件(index.php)
<?php
// 自动加载类
spl_autoload_register(function ($class) {
require_once str_replace('\\', '/', $class) . '.php';
});
// 获取请求路径
$request = $_SERVER['REQUEST_URI'];
$request = str_replace('/mvc/', '', $request);
// 简单路由
switch ($request) {
case '':
case 'home':
$controller = new \controllers\HomeController();
$controller->index();
break;
default:
http_response_code(404);
echo '404 Not Found';
break;
}
?>
控制器示例(HomeController.php)
<?php
namespace controllers;
use models\HomeModel;
class HomeController {
public function index() {
$model = new HomeModel();
$data = $model->getData();
require_once '../views/home.php';
}
}
?>
模型示例(HomeModel.php)
<?php
namespace models;
class HomeModel {
public function getData() {
return [
'title' => 'MVC示例',
'content' => '这是一个简单的MVC实现'
];
}
}
?>
视图示例(home.php)
<!DOCTYPE html>
<html>
<head>
<title><?php echo $data['title']; ?></title>
</head>
<body>
<h1><?php echo $data['title']; ?></h1>
<p><?php echo $data['content']; ?></p>
</body>
</html>
扩展路由系统
对于更复杂的应用,可以实现一个简单的路由类:
class Router {
private $routes = [];
public function addRoute($path, $handler) {
$this->routes[$path] = $handler;
}
public function dispatch($request) {
if (isset($this->routes[$request])) {
$handler = $this->routes[$request];
call_user_func($handler);
} else {
http_response_code(404);
echo '404 Not Found';
}
}
}
数据库连接
在模型中添加数据库连接:
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO(
'mysql:host=localhost;dbname=test',
'username',
'password'
);
}
public function query($sql, $params = []) {
$stmt = $this->connection->prepare($sql);
$stmt->execute($params);
return $stmt;
}
}
注意事项
- 确保所有PHP文件使用正确的命名空间
- 视图文件只应包含展示逻辑,避免复杂业务逻辑
- 控制器应保持精简,主要负责协调模型和视图
- 考虑使用Composer进行依赖管理
- 对于生产环境,需要添加更多错误处理和安全性措施






