mvc实现 PHP
MVC 实现 PHP
MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的逻辑、数据和界面。在 PHP 中实现 MVC 可以提高代码的可维护性和可扩展性。

项目结构
典型的 MVC 项目结构如下:

project/
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── core/
├── public/
│ └── index.php
└── config/
controllers处理用户请求和业务逻辑models负责数据操作和业务规则views负责展示数据core包含框架核心类如路由、数据库连接等public是入口文件和静态资源目录config存放配置文件
核心组件实现
路由系统
路由负责解析 URL 并调用相应的控制器和方法:
// core/Router.php
class Router {
protected $routes = [];
public function add($uri, $controller, $method) {
$this->routes[$uri] = [
'controller' => $controller,
'method' => $method
];
}
public function dispatch($uri) {
if (array_key_exists($uri, $this->routes)) {
$controller = $this->routes[$uri]['controller'];
$method = $this->routes[$uri]['method'];
$controller = new $controller();
$controller->$method();
} else {
throw new Exception("Route not found");
}
}
}
基础控制器
// core/Controller.php
class Controller {
protected function view($view, $data = []) {
extract($data);
require_once "../app/views/$view.php";
}
protected function model($model) {
require_once "../app/models/$model.php";
return new $model();
}
}
示例实现
模型示例
// models/User.php
class User {
private $db;
public function __construct() {
$this->db = new Database(); // 假设已实现数据库类
}
public function getUsers() {
$this->db->query("SELECT * FROM users");
return $this->db->resultSet();
}
}
控制器示例
// controllers/Users.php
class Users extends Controller {
public function index() {
$user = $this->model('User');
$data = $user->getUsers();
$this->view('users/index', $data);
}
}
视图示例
<!-- views/users/index.php -->
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>User List</h1>
<ul>
<?php foreach ($data as $user): ?>
<li><?php echo $user['name']; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
入口文件
// public/index.php
require_once '../app/core/Router.php';
require_once '../app/core/Controller.php';
$router = new Router();
// 添加路由
$router->add('/', 'Home', 'index');
$router->add('/users', 'Users', 'index');
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$router->dispatch($uri);
数据库连接
// core/Database.php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $stmt;
private $dbh;
public function __construct() {
$dsn = "mysql:host={$this->host};dbname={$this->dbname}";
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
die($e->getMessage());
}
}
public function query($sql) {
$this->stmt = $this->dbh->prepare($sql);
}
public function bind($param, $value, $type = null) {
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute() {
return $this->stmt->execute();
}
public function resultSet() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
自动加载
使用 Composer 的自动加载或实现简单的自动加载:
// autoload.php
spl_autoload_register(function($className) {
$file = __DIR__ . '/../app/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require $file;
}
});
配置管理
// config/config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'mvc_app');
这个实现展示了 PHP 中 MVC 模式的基本结构。实际项目中可能需要更复杂的路由系统、中间件支持、依赖注入等高级功能。






