PHP框架核心运行原理解析
PHP框架核心运行原理解析
用了这么多年框架,你知道框架是怎么跑起来的吗?框架的核心就几件事:路由解析、依赖注入、请求处理、响应返回。今天把这些核心原理说清楚。
所有框架都从一个入口文件开始。Laravel的public/index.php、ThinkPHP的public/index.php都是这样。
```php
require __DIR__ . '/../vendor/autoload.php';
$app = require_once __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = $kernel->handle($request = Request::capture())->send();
$kernel->terminate($request, $response);
?>
```
路由系统把URL映射到控制器方法。框架用正则表达式匹配URL参数。
```php
class Router
{
private array $routes = [];
public function get(string $uri, callable $handler): void
{
$this->routes['GET'][$uri] = $handler;
}
public function post(string $uri, callable $handler): void
{
$this->routes['POST'][$uri] = $handler;
}
public function dispatch(string $method, string $uri): mixed
{
$uri = parse_url($uri, PHP_URL_PATH);
foreach ($this->routes[$method] ?? [] as $pattern => $handler) {
$regex = preg_replace('/\{(\w+)\}/', '(\w+)', $pattern);
$regex = "#^$regex$#";
if (preg_match($regex, $uri, $matches)) {
array_shift($matches);
return $handler(...$matches);
}
}
throw new RuntimeException("404 Not Found");
}
}
$router = new Router();
$router->get('/users/{id}', function ($id) {
return "用户ID: $id";
});
echo $router->dispatch('GET', '/users/42');
?>
```
依赖注入容器是框架的另一个核心。它管理对象的创建和依赖解析。
```php
class Container
{
private array $bindings = [];
public function bind(string $abstract, callable $factory): void
{
$this->bindings[$abstract] = $factory;
}
public function make(string $abstract): mixed
{
if (isset($this->bindings[$abstract])) {
return ($this->bindings[$abstract])($this);
}
return $this->autoResolve($abstract);
}
private function autoResolve(string $class): object
{
$ref = new ReflectionClass($class);
$ctor = $ref->getConstructor();
if ($ctor === null) return $ref->newInstance();
$deps = [];
foreach ($ctor->getParameters() as $param) {
$type = $param->getType();
if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
$deps[] = $this->make($type->getName());
}
}
return $ref->newInstanceArgs($deps);
}
}
class UserController
{
public function __construct(private UserService $service) {}
public function show(int $id): string { return "用户: $id"; }
}
$container = new Container();
$controller = $container->make(UserController::class);
echo $controller->show(1);
?>
```
中间件是请求处理管道。请求经过一层层中间件,每层可以决定放行还是拦截。
```php
class Pipeline
{
private array $middlewares = [];
public function add(callable $middleware): void
{
$this->middlewares[] = $middleware;
}
public function run(mixed $request, callable $core): mixed
{
$pipeline = $core;
foreach (array_reverse($this->middlewares) as $mw) {
$pipeline = fn($req) => $mw($req, $pipeline);
}
return $pipeline($request);
}
}
?>
```
Eloquent ORM的链式调用也很简单,每个方法返回$this。
```php
class QueryBuilder
{
private array $wheres = [];
public function where(string $col, mixed $val): static
{
$this->wheres[] = [$col, $val];
return $this;
}
public function get(): array
{
return $this->wheres;
}
}
$result = (new QueryBuilder())->where('status', 1)->where('age', 18)->get();
print_r($result);
?>
```
框架这东西,用多了就离不开。但理解背后的原理后,出问题的时候就能快速定位,还能根据自己的需求做定制。一个合格的PHP开发者,至少要知道容器、路由、中间件这三个核心是怎么实现的。
