php简单实现/mvc

实现PHP的MVC框架
MVC(Model-View-Controller)是一种常见的软件设计模式,用于分离应用程序的逻辑、数据和界面。以下是一个简单的PHP MVC实现示例:
目录结构
app/
controllers/
HomeController.php
models/
UserModel.php
views/
home/
index.php
public/
index.php
入口文件 (public/index.php)
<?php
require_once '../app/bootstrap.php';
$router = new Router();
$router->dispatch();
引导文件 (app/bootstrap.php)
<?php
require_once 'core/Router.php';
require_once 'core/Controller.php';
require_once 'core/Model.php';
spl_autoload_register(function($className) {
$file = str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require $file;
}
});
路由类 (core/Router.php)
<?php
class Router {
protected $controller = 'HomeController';
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]) . 'Controller';
unset($url[0]);
}
require_once '../app/controllers/' . $this->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);
}
public function parseUrl() {
if (isset($_GET['url'])) {
return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
}
}
基础控制器 (core/Controller.php)
<?php
class Controller {
public function model($model) {
require_once '../app/models/' . $model . '.php';
return new $model();
}
public function view($view, $data = []) {
require_once '../app/views/' . $view . '.php';
}
}
基础模型 (core/Model.php)
<?php
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
}
示例控制器 (app/controllers/HomeController.php)
<?php
class HomeController extends Controller {
public function index() {
$data = [
'title' => 'Welcome to MVC'
];
$this->view('home/index', $data);
}
}
示例视图 (app/views/home/index.php)
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $title; ?></h1>
</body>
</html>
示例模型 (app/models/UserModel.php)
<?php
class UserModel extends Model {
public function getUsers() {
$stmt = $this->db->query('SELECT * FROM users');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
.htaccess文件 (public/.htaccess)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
这个实现展示了MVC框架的基本结构,可以根据需要进行扩展。关键点是分离关注点:模型处理数据,视图处理显示,控制器协调两者。







