php实现mvc框架
PHP 实现 MVC 框架
MVC(Model-View-Controller)是一种常见的软件架构模式,用于分离应用程序的业务逻辑、用户界面和用户输入。以下是实现一个基础 PHP MVC 框架的关键步骤。
目录结构
一个典型的 MVC 框架目录结构如下:
app/
controllers/
models/
views/
public/
index.php
.htaccess
core/
Router.php
Controller.php
Model.php
View.php
路由实现
路由负责解析 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("No route found for URI: $uri");
}
}
}
控制器基类
控制器负责处理用户请求并调用模型和视图:
class Controller {
protected $model;
protected $view;
public function __construct() {
$this->view = new View();
}
public function setModel($model) {
$this->model = $model;
}
}
视图基类
视图负责渲染模板并输出 HTML:
class View {
public function render($template, $data = []) {
extract($data);
include "app/views/$template.php";
}
}
模型基类
模型负责数据操作和业务逻辑:
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
}
入口文件
public/index.php 是框架的入口点:
require_once '../core/Router.php';
require_once '../core/Controller.php';
require_once '../core/Model.php';
require_once '../core/View.php';
$router = new Router();
$router->addRoute('/', 'HomeController', 'index');
$router->addRoute('/about', 'AboutController', 'index');
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$router->dispatch($uri);
.htaccess 配置
确保所有请求都重定向到 index.php:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
使用示例
创建一个简单的控制器和视图:
// app/controllers/HomeController.php
class HomeController extends Controller {
public function index() {
$data = ['title' => 'Home Page'];
$this->view->render('home/index', $data);
}
}
<!-- app/views/home/index.php -->
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1>Welcome to the Home Page</h1>
</body>
</html>
数据库操作
在模型中实现数据操作:
// app/models/UserModel.php
class UserModel extends Model {
public function getUsers() {
$stmt = $this->db->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
自动加载
使用 spl_autoload_register 自动加载类文件:
spl_autoload_register(function ($class) {
$file = __DIR__ . '/../app/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
}
});
以上实现提供了一个基础的 PHP MVC 框架结构,可以根据需求进一步扩展功能,如中间件、依赖注入等。







