php实现mvc
PHP 实现 MVC 架构
MVC(Model-View-Controller)是一种常见的软件设计模式,用于分离应用程序的逻辑、数据和界面。以下是使用 PHP 实现 MVC 架构的关键步骤。
目录结构
典型的 MVC 目录结构如下:
app/
├── controllers/
├── models/
├── views/
public/
├── index.php
创建入口文件
在 public/index.php 中初始化应用程序并处理请求:
require_once '../app/bootstrap.php';
$app = new Core\App();
$app->run();
核心 App 类
Core/App.php 负责路由解析和调度:
class App {
protected $controller = 'Home';
protected $method = 'index';
protected $params = [];
public function __construct() {
$url = $this->parseUrl();
if (file_exists('../app/controllers/' . ucfirst($url[0]) . 'Controller.php')) {
$this->controller = ucfirst($url[0]);
unset($url[0]);
}
require_once '../app/controllers/' . $this->controller . 'Controller.php';
$this->controller = new $this->controller;
if (isset($url[1])) {
if (method_exists($this->controller, $url[1])) {
$this->method = $url[1];
unset($url[1]);
}
}
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->controller, $this->method], $this->params);
}
protected function parseUrl() {
if (isset($_GET['url'])) {
return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
}
}
控制器示例
controllers/HomeController.php:
class HomeController {
public function index($name = '') {
$user = $this->model('User');
$user->name = $name;
$this->view('home/index', ['name' => $user->name]);
}
protected function model($model) {
require_once '../app/models/' . $model . '.php';
return new $model();
}
protected function view($view, $data = []) {
require_once '../app/views/' . $view . '.php';
}
}
模型示例
models/User.php:
class User {
public $name;
}
视图示例
views/home/index.php:
<!DOCTYPE html>
<html>
<head>
<title>MVC Example</title>
</head>
<body>
<h1>Hello <?php echo htmlspecialchars($name); ?>!</h1>
</body>
</html>
URL 重写
在 public/.htaccess 中配置 URL 重写规则:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
自动加载
在 app/bootstrap.php 中实现自动加载:
spl_autoload_register(function ($className) {
$file = '../app/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require_once $file;
}
});
数据库集成
在模型中集成数据库操作:
class Post {
private $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
public function getAll() {
$stmt = $this->db->query('SELECT * FROM posts');
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
}
这种实现方式提供了清晰的关注点分离,使代码更易于维护和扩展。可以根据项目需求进一步扩展,例如添加中间件、依赖注入容器等高级功能。







