php 简单框架实现
实现一个简单的 PHP 框架
以下是一个基础 PHP 框架的实现思路,包含路由、控制器和视图的核心功能。框架结构清晰,适合学习或小型项目。
目录结构
/app
/controllers
HomeController.php
/views
home.php
/public
index.php
.htaccess
/config
routes.php
路由系统
在 /config/routes.php 中定义路由规则:
<?php
return [
'/' => ['HomeController', 'index'],
'/about' => ['HomeController', 'about']
];
前端控制器
/public/index.php 作为入口文件:

<?php
require_once '../config/routes.php';
$request = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (array_key_exists($request, $routes)) {
$controller = $routes[$request][0];
$method = $routes[$request][1];
require_once "../app/controllers/$controller.php";
$controllerInstance = new $controller();
$controllerInstance->$method();
} else {
header("HTTP/1.0 404 Not Found");
echo '404 Not Found';
}
控制器示例
/app/controllers/HomeController.php:
<?php
class HomeController {
public function index() {
require_once '../app/views/home.php';
}
public function about() {
echo 'About Page';
}
}
视图文件
/app/views/home.php:

<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to our simple PHP framework</h1>
</body>
</html>
URL重写
/public/.htaccess 文件配置:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
数据库集成
添加简单的数据库连接功能,创建 /config/database.php:
<?php
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO(
'mysql:host=localhost;dbname=test',
'username',
'password'
);
}
public function query($sql, $params = []) {
$stmt = $this->connection->prepare($sql);
$stmt->execute($params);
return $stmt;
}
}
自动加载
实现简单的类自动加载,在入口文件添加:
spl_autoload_register(function ($class) {
$file = '../app/controllers/' . $class . '.php';
if (file_exists($file)) {
require_once $file;
}
});
这个简单框架包含了 MVC 的基本结构,可以进一步扩展添加中间件、依赖注入容器等功能。实际项目中建议使用成熟的框架如 Laravel 或 Symfony。






