php mvc 实现
PHP MVC 实现方法
MVC(Model-View-Controller)是一种常见的架构模式,用于分离业务逻辑、数据和界面。以下是实现PHP MVC框架的核心步骤:
目录结构设计
创建以下基础目录结构:
app/:存放核心逻辑models/:数据模型views/:视图模板controllers/:控制器
public/:Web入口index.php:前端控制器
config/:配置文件
前端控制器
在public/index.php中初始化应用:
require '../app/bootstrap.php';
$app = new Application();
$app->run();
路由解析
创建路由解析器处理URL映射:
class Router {
protected $routes = [];
public function addRoute($uri, $controller) {
$this->routes[$uri] = $controller;
}
public function dispatch($uri) {
if (array_key_exists($uri, $this->routes)) {
return $this->routes[$uri];
}
throw new Exception('No route found');
}
}
控制器实现
示例控制器基类:
abstract class Controller {
protected function view($view, $data = []) {
extract($data);
require "../app/views/{$view}.php";
}
}
模型层
基础模型类示例:
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
}
}
视图层
简单的视图模板示例(views/home.php):

<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1><?= $content ?></h1>
</body>
</html>
自动加载
实现PSR-4自动加载:
spl_autoload_register(function ($class) {
$file = str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
}
});
依赖注入
简单的依赖容器示例:
class Container {
protected $instances = [];
public function set($key, $value) {
$this->instances[$key] = $value;
}
public function get($key) {
return $this->instances[$key];
}
}
进阶优化
路由改进
支持动态路由参数:
public function dispatch($uri) {
foreach ($this->routes as $pattern => $controller) {
if (preg_match("#^$pattern$#", $uri, $matches)) {
array_shift($matches);
return [$controller, $matches];
}
}
}
中间件支持
添加中间件处理层:

class Middleware {
public function handle($request, Closure $next) {
// 前置处理
$response = $next($request);
// 后置处理
return $response;
}
}
ORM集成
集成Eloquent ORM示例:
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'dbname',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
]);
$capsule->bootEloquent();
模板引擎
集成Twig模板引擎:
$loader = new \Twig\Loader\FilesystemLoader('../app/views');
$twig = new \Twig\Environment($loader, [
'cache' => '../storage/cache',
]);
echo $twig->render('index.twig', ['name' => 'World']);
安全注意事项
输入验证和过滤:
$cleanInput = filter_input(INPUT_GET, 'param', FILTER_SANITIZE_STRING);
CSRF防护实现:
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
密码哈希处理:
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
这些实现方法涵盖了PHP MVC框架的核心组件,可以根据项目需求进行扩展和调整。






