php mvc架构的简单例子
以下是一个简单的 PHP MVC 架构示例,包含基本的模型(Model)、视图(View)和控制器(Controller)结构:
目录结构
project/
├── app/
│ ├── controllers/
│ │ ├── HomeController[文].php
│ │ └── UserController[章].php
│ ├── models/
│ │ └── User.php
│ └── views/
│ ├── home/
│ │ └── index.php
│ └── user/
│ └── list.php
├── public/
│ └── index.php
└── .htaccess
1.入口文件 public/index.php
<?php// 自动加载类spl_autoload_register(function ($class) { $file = __DIR__ . '/../app/' . str_replace('\\', '/', $class) . '.php'; if (file_exists($file)) { require $file; }});// 获取请求路径$request = $_SERVER['REQUEST_URI'];$path = parse_url($request, PHP_URL_PATH);// 简单路由switch ($path) { case '/': $controller = new \controllers\HomeController(); $controller->index(); break; case '/user/list': $controller = new \controllers\UserController(); $controller->list(); break; default: http_response_code(404); echo 'Page not found'; break;}2. 控制器 app/controllers/HomeController.php
<?phpnamespace controllers;class HomeController { public function index() { // 加载视图 require __DIR__ . '/../views/home/index.php'; }}3. 控制器 app/controllers/UserController.php
<?phpnamespace controllers;use models\User;class UserController { public function list() { // 获取数据 $userModel = new User(); $users = $userModel->getAllUsers(); // 传递数据到视图 require __DIR__ . '/../views/user/list.php'; }}4. 模型 app/models/User.php
<?phpnamespace models;class User { // 模拟数据库数据 public function getAllUsers() { return [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'] ]; }}5. 视图 app/views/home/index.php
<!DOCTYPE html><html><head> <title>Home</title></head><body> <h1>Welcome to Home Page</h1> <a href="/user/list">View Users</a></body></html>
6. 视图 app/views/user/list.php
<!DOCTYPE html><html><head> <title>User List</title></head><body> <h1>User List</h1> <ul> <?php foreach ($users as $user): ?> <li><?= htmlspecialchars($user['name']) ?></li> <?php endforeach; ?> </ul> <a href="/">Back to Home</a></body></html>
7. .htaccess 文件(用于URL重写)
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /public/index.php [L]</IfModule>运行说明
将项目放在 Web 服务器的根目录(如 Apache 的
htdocs)访问
http://localhost/显示首页访问
http://localhost/user/list显示用户列表
