php 简单框架实现
实现一个简单的 PHP 框架
PHP 框架的核心通常包含路由、请求处理、控制器和视图渲染。以下是一个极简框架的实现示例,适合理解框架的基本原理。
目录结构
/myframework
/app
/controllers
HomeController.php
/views
home.php
/public
index.php
/core
Router.php
Request.php
Controller.php
核心路由实现
在 /core/Router.php 中定义路由解析逻辑:
class Router {
protected $routes = [];
public function addRoute($method, $uri, $controller) {
$this->routes[$method][$uri] = $controller;
}
public function dispatch($uri, $method) {
if (isset($this->routes[$method][$uri])) {
$controller = $this->routes[$method][$uri];
$this->callAction(...explode('@', $controller));
} else {
throw new Exception("Route not found");
}
}
protected function callAction($controller, $action) {
$controller = new $controller;
$controller->$action();
}
}
请求处理基础
在 /core/Request.php 中封装请求数据:

class Request {
public static function uri() {
return trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
}
public static function method() {
return $_SERVER['REQUEST_METHOD'];
}
}
基础控制器
在 /core/Controller.php 中定义控制器基类:
class Controller {
public function view($view, $data = []) {
extract($data);
require "../app/views/{$view}.php";
}
}
入口文件
在 /public/index.php 中初始化框架:

require '../core/Router.php';
require '../core/Request.php';
require '../core/Controller.php';
$router = new Router();
// 注册路由
$router->addRoute('GET', '', 'HomeController@index');
$router->addRoute('GET', 'about', 'HomeController@about');
$uri = Request::uri();
$method = Request::method();
$router->dispatch($uri, $method);
示例控制器
在 /app/controllers/HomeController.php 中实现控制器:
class HomeController extends Controller {
public function index() {
$this->view('home', ['title' => 'Welcome']);
}
public function about() {
$this->view('home', ['title' => 'About Us']);
}
}
视图文件
在 /app/views/home.php 中创建简单视图:
<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1><?= $title ?></h1>
</body>
</html>
运行方式
- 将项目放在 PHP 环境(如 Apache 或 Nginx)的 web 目录
- 配置 web 服务器将请求指向
/public/index.php - 访问
http://localhost或http://localhost/about查看效果
这个实现展示了框架的基本组件,可根据需要扩展数据库支持、中间件、依赖注入等功能。






