php实现mvc
PHP实现MVC架构
MVC(Model-View-Controller)是一种常用的软件设计模式,用于分离业务逻辑、数据和界面。以下是PHP实现MVC架构的核心要点:
目录结构设计
典型的MVC目录结构如下:
app/
├── controllers/
├── models/
├── views/
public/
├── index.php
入口文件
在public/index.php中设置前端控制器:
require '../app/bootstrap.php';
$router = new Router();
$router->dispatch();
路由处理
创建简单的路由类:
class Router {
public function dispatch() {
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$url = explode('/', trim($url, '/'));
$controller = isset($url[0]) ? ucfirst($url[0]) . 'Controller' : 'HomeController';
$action = isset($url[1]) ? $url[1] : 'index';
if (class_exists($controller)) {
$controllerInstance = new $controller();
if (method_exists($controllerInstance, $action)) {
$controllerInstance->$action();
} else {
// 处理404
}
} 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' => 'MVC Example'];
}
}
视图处理
class View {
protected $path;
public function __construct($viewPath) {
$this->path = "app/views/{$viewPath}.php";
}
public function render($data = []) {
extract($data);
include $this->path;
}
}
视图文件示例
app/views/home/index.php:
<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1><?= $content ?></h1>
</body>
</html>
数据库集成
在模型中集成数据库操作:
class UserModel {
private $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
}
public function getUsers() {
$stmt = $this->db->query('SELECT * FROM users');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
自动加载
实现PSR-4自动加载:
spl_autoload_register(function ($class) {
$file = __DIR__ . '/../' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
}
});
配置管理
创建配置文件:
return [
'database' => [
'host' => 'localhost',
'dbname' => 'test',
'user' => 'root',
'pass' => ''
]
];
这种实现方式提供了MVC的基本结构,可以根据项目需求进一步扩展,如添加中间件、依赖注入等功能。







