mvc实现 PHP
MVC 实现 PHP 的步骤
MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的业务逻辑、用户界面和控制逻辑。以下是使用 PHP 实现 MVC 的基本方法。
创建目录结构
一个典型的 MVC 应用程序通常包含以下目录结构:
app/
controllers/
models/
views/
public/
index.php
app/ 目录包含控制器、模型和视图,public/ 目录是 Web 服务器的根目录,index.php 是入口文件。
定义入口文件
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 = !empty($urlParts[0]) ? $urlParts[0] : 'Home';
$actionName = !empty($urlParts[1]) ? $urlParts[1] : 'index';
$controllerClass = ucfirst($controllerName) . 'Controller';
$controllerFile = '../app/controllers/' . $controllerClass . '.php';
if (file_exists($controllerFile)) {
require_once $controllerFile;
$controller = new $controllerClass();
$controller->$actionName();
} else {
require_once '../app/views/errors/404.php';
}
}
}
创建控制器
控制器负责处理用户请求并调用模型和视图:
class HomeController {
public function index() {
$model = new HomeModel();
$data = $model->getData();
require_once '../app/views/home/index.php';
}
}
创建模型
模型负责处理数据逻辑和数据库交互:
class HomeModel {
public function getData() {
return ['title' => 'Welcome to MVC PHP'];
}
}
创建视图
视图负责显示数据,通常是一个 HTML 模板:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $data['title']; ?></title>
</head>
<body>
<h1><?php echo $data['title']; ?></h1>
</body>
</html>
自动加载类
使用 spl_autoload_register 自动加载类文件,避免手动包含每个文件:
spl_autoload_register(function ($className) {
$file = '../app/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require_once $file;
}
});
使用 Composer 管理依赖
如果需要使用第三方库,可以通过 Composer 进行管理。创建一个 composer.json 文件:
{
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
运行 composer install 后,类可以通过命名空间自动加载。
数据库连接
在模型中集成数据库操作,例如使用 PDO:
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
错误处理
添加自定义错误处理机制,例如 404 页面:
set_exception_handler(function ($exception) {
require_once '../app/views/errors/500.php';
});
安全性增强
确保输入数据经过过滤和验证,防止 SQL 注入和 XSS 攻击:
$input = filter_input(INPUT_GET, 'param', FILTER_SANITIZE_STRING);
使用 .htaccess 重写 URL
在 public/ 目录下创建 .htaccess 文件,将所有请求重定向到 index.php:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
示例完整流程
- 用户访问
/home/index。 - 路由器解析 URL,调用
HomeController的index方法。 - 控制器调用
HomeModel获取数据。 - 控制器加载
views/home/index.php并传递数据。 - 视图显示数据给用户。
通过以上步骤,可以实现一个基本的 PHP MVC 应用程序框架。根据需求可以进一步扩展,例如添加中间件、依赖注入等功能。






