php mvc实现
PHP MVC 实现方法
MVC(Model-View-Controller)是一种常用的设计模式,用于分离应用程序的逻辑、数据和界面。以下是实现 PHP MVC 框架的关键步骤。
目录结构设计
创建清晰的目录结构是 MVC 实现的基础。典型的目录结构如下:
app/
controllers/
models/
views/
public/
index.php
assets/
app/ 目录包含核心 MVC 组件,public/ 是入口文件和静态资源。
入口文件设置
public/index.php 是应用程序的唯一入口,负责初始化并路由请求:
<?php
require_once '../app/bootstrap.php';
$router = new Router();
$router->dispatch();
路由处理
路由组件解析 URL 并调用相应的控制器和方法:
class Router {
public function dispatch() {
$url = $_SERVER['REQUEST_URI'];
$urlParts = explode('/', trim($url, '/'));
$controllerName = isset($urlParts[0]) ? $urlParts[0] : 'home';
$actionName = isset($urlParts[1]) ? $urlParts[1] : 'index';
$controllerClass = ucfirst($controllerName) . 'Controller';
if (class_exists($controllerClass)) {
$controller = new $controllerClass();
$controller->{$actionName}();
} else {
// 处理 404
}
}
}
控制器实现
控制器处理用户请求并协调模型和视图:
class HomeController {
public function index() {
$model = new HomeModel();
$data = $model->getData();
$view = new View('home/index');
$view->render($data);
}
}
模型设计
模型负责数据操作和业务逻辑:
class HomeModel {
public function getData() {
// 数据库查询或其他数据操作
return ['title' => 'Welcome', 'content' => 'Hello MVC'];
}
}
视图渲染
视图负责展示数据,通常使用模板引擎或原生 PHP:
class View {
private $template;
public function __construct($template) {
$this->template = 'app/views/' . $template . '.php';
}
public function render($data = []) {
extract($data);
include $this->template;
}
}
视图文件示例 app/views/home/index.php:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $content; ?></h1>
</body>
</html>
数据库集成
模型通常需要与数据库交互,可以封装数据库连接:
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
}
public function query($sql, $params = []) {
$stmt = $this->connection->prepare($sql);
$stmt->execute($params);
return $stmt;
}
}
模型中使用数据库类:
class PostModel {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getPosts() {
$result = $this->db->query('SELECT * FROM posts');
return $result->fetchAll(PDO::FETCH_ASSOC);
}
}
自动加载
使用自动加载避免手动包含文件:
spl_autoload_register(function ($className) {
$file = __DIR__ . '/../app/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require $file;
}
});
配置管理
将配置参数集中管理:
class Config {
public static $settings = [
'db' => [
'host' => 'localhost',
'user' => 'root',
'password' => '',
'name' => 'test'
]
];
}
错误处理
实现自定义错误处理:
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
set_exception_handler(function($e) {
echo '<h1>Error</h1>';
echo '<p>' . $e->getMessage() . '</p>';
});
安全考虑
实现基本安全措施:
class Input {
public static function sanitize($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
public static function get($key) {
return isset($_GET[$key]) ? self::sanitize($_GET[$key]) : null;
}
public static function post($key) {
return isset($_POST[$key]) ? self::sanitize($_POST[$key]) : null;
}
}
扩展性设计
为框架添加中间件支持:
class Middleware {
public static function run($middlewares, $callback) {
foreach ($middlewares as $middleware) {
$middleware::handle();
}
$callback();
}
}
class AuthMiddleware {
public static function handle() {
if (!isset($_SESSION['user'])) {
header('Location: /login');
exit;
}
}
}
使用中间件:
Middleware::run([AuthMiddleware::class], function() {
// 受保护的代码
});
以上步骤展示了如何从零开始实现一个基本的 PHP MVC 框架。实际项目中可能需要更多功能,如依赖注入、ORM、缓存等,但这些核心组件已经构成了 MVC 的基本结构。







