php mvc实现
PHP MVC 实现方法
MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的逻辑、数据和界面。以下是实现PHP MVC框架的基本方法。
目录结构
app/
controllers/
models/
views/
public/
index.php
入口文件
在public/index.php中设置入口点,负责初始化应用程序并路由请求。
<?php
require_once '../app/bootstrap.php';
$app = new App();
路由处理
创建路由类Router,解析URL并调用相应的控制器和方法。
class Router {
protected $routes = [];
public function addRoute($route, $controller, $action) {
$this->routes[$route] = ['controller' => $controller, 'action' => $action];
}
public function dispatch($uri) {
if (array_key_exists($uri, $this->routes)) {
$controller = $this->routes[$uri]['controller'];
$action = $this->routes[$uri]['action'];
$controller = new $controller();
$controller->$action();
} else {
throw new Exception("Route not found");
}
}
}
控制器
控制器处理用户输入并调用模型和视图。示例控制器HomeController:
class HomeController {
public function index() {
$model = new HomeModel();
$data = $model->getData();
require_once '../app/views/home/index.php';
}
}
模型
模型处理数据逻辑,通常与数据库交互。示例模型HomeModel:
class HomeModel {
public function getData() {
return ['title' => 'Welcome', 'content' => 'This is the home page'];
}
}
视图
视图负责显示数据。示例视图home/index.php:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $data['title']; ?></title>
</head>
<body>
<h1><?php echo $data['content']; ?></h1>
</body>
</html>
自动加载
使用spl_autoload_register自动加载类文件。
spl_autoload_register(function ($class) {
$file = '../app/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require_once $file;
}
});
数据库集成
集成数据库操作,例如使用PDO。
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;
}
}
配置管理
创建配置文件config.php集中管理配置。
return [
'database' => [
'host' => 'localhost',
'dbname' => 'test',
'username' => 'root',
'password' => ''
]
];
错误处理
设置自定义错误和异常处理。

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
set_exception_handler(function ($exception) {
echo "Uncaught exception: " . $exception->getMessage();
});
通过以上步骤,可以构建一个基本的PHP MVC框架。根据需求进一步扩展功能,例如中间件、依赖注入等。






