php 简单框架实现
PHP 简单框架实现
核心组件
一个简单的 PHP 框架通常包含路由、控制器、模型和视图等核心组件。以下是一个基础实现的示例:
1. 文件结构
/app
/controllers
HomeController.php
/models
User.php
/views
home.php
/public
index.php
.htaccess
/vendor
(依赖库)
2. 入口文件 (public/index.php)
<?php
require __DIR__ . '/../app/bootstrap.php';
$router = new Router();
$router->dispatch();
3. 路由实现 (app/Router.php)
class Router {
public function dispatch() {
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$routes = [
'/' => 'HomeController@index',
'/user' => 'UserController@show'
];
if (array_key_exists($uri, $routes)) {
list($controller, $method) = explode('@', $routes[$uri]);
$controller = new $controller();
$controller->$method();
} else {
http_response_code(404);
echo '404 Not Found';
}
}
}
4. 控制器示例 (app/controllers/HomeController.php)
class HomeController {
public function index() {
$data = ['title' => 'Home Page'];
require __DIR__ . '/../views/home.php';
}
}
5. 视图示例 (app/views/home.php)
<!DOCTYPE html>
<html>
<head>
<title><?= $data['title'] ?></title>
</head>
<body>
<h1>Welcome to Simple PHP Framework</h1>
</body>
</html>
数据库连接
模型基础类 (app/Model.php)
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
}
}
自动加载
bootstrap.php

spl_autoload_register(function ($class) {
$file = __DIR__ . '/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
}
});
.htaccess 配置
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
这个简单框架实现了基本的MVC结构,包含路由分发、控制器处理、视图渲染和数据库连接等核心功能。可以根据需要扩展中间件、依赖注入容器等高级特性。






