乐于分享
好东西不私藏

Laravel核心源码解读

Laravel核心源码解读

Laravel是PHP最流行的框架之一,本文深入解读Laravel的核心源码,帮助你理解框架的设计思想和实现原理。

一、Laravel架构概述

1.1 目录结构解析

【Laravel核心目录结构】

laravel/framework/src/Illuminate/
├── Auth/                 # 认证模块
├── Broadcasting/         # 广播模块
├── Bus/                  # 命令总线
├── Cache/                # 缓存模块
├── Config/               # 配置模块
├── Console/              # 控制台命令
├── Container/            # IoC容器(核心)
├── Contracts/            # 接口契约
├── Cookie/               # Cookie处理
├── Database/             # 数据库ORM
├── Encryption/           # 加密模块
├── Events/               # 事件系统
├── Filesystem/           # 文件系统
├── Foundation/           # 框架基础
├── Hashing/              # 哈希模块
├── Http/                 # HTTP处理
├── Log/                  # 日志模块
├── Mail/                 # 邮件模块
├── Notifications/        # 通知模块
├── Pagination/           # 分页模块
├── Pipeline/             # 管道(中间件核心)
├── Queue/                # 队列模块
├── Redis/                # Redis模块
├── Routing/              # 路由模块
├── Session/              # 会话模块
├── Support/              # 辅助工具
├── Translation/          # 翻译模块
├── Validation/           # 验证模块
└── View/                 # 视图模块

1.2 核心组件关系

【Laravel核心组件关系图】

                    ┌─────────────────┐
                    │   Application   │
                    │   (容器核心)     │
                    └────────┬────────┘
                             │
        ┌────────────────────┼────────────────────┐
        │                    │                    │
        ▼                    ▼                    ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│  Service      │   │   Router      │   │   Pipeline    │
│  Provider     │   │   (路由)       │   │   (管道)      │
└───────┬───────┘   └───────┬───────┘   └───────┬───────┘
        │                   │                   │
        ▼                   ▼                   ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│  Facades      │   │  Controller   │   │  Middleware   │
│  (门面)        │   │  (控制器)     │   │  (中间件)     │
└───────────────┘   └───────────────┘   └───────────────┘

二、服务容器源码解析

2.1 Container核心实现

<?php
/**
 * Laravel容器核心源码解析
 * 文件位置:Illuminate/Container/Container.php
 */


namespaceIlluminate\Container;

classContainerimplementsContainerContract{

/**
     * 当前全局容器实例
     */

protectedstatic $instance;

/**
     * 已解析的共享实例(单例)
     */

protected $instances = [];

/**
     * 容器绑定
     * 存储所有的绑定关系
     */

protected $bindings = [];

/**
     * 别名映射
     */

protected $aliases = [];

/**
     * 绑定服务到容器
     * 
     * @param string $abstract 抽象类型(接口或别名)
     * @param mixed $concrete 具体实现
     * @param bool $shared 是否单例
     */

publicfunctionbind($abstract, $concrete = null, $shared = false){
// 移除旧的实例和别名
$this->dropStaleInstances($abstract);

// 如果没有提供具体实现,使用抽象类型本身
if (is_null($concrete)) {
            $concrete = $abstract;
        }

// 如果不是闭包,包装成闭包
if (!$concrete instanceof Closure) {
            $concrete = $this->getClosure($abstract, $concrete);
        }

// 存储绑定信息
$this->bindings[$abstract] = compact('concrete''shared');
    }

/**
     * 绑定单例
     */

publicfunctionsingleton($abstract, $concrete = null){
$this->bind($abstract, $concrete, true);
    }

/**
     * 绑定已存在的实例
     */

publicfunctioninstance($abstract, $instance){
$this->instances[$abstract] = $instance;
return $instance;
    }

/**
     * 从容器解析服务
     * 这是容器最核心的方法
     */

publicfunctionmake($abstract, array $parameters = []){
return$this->resolve($abstract, $parameters);
    }

/**
     * 解析服务的核心逻辑
     */

protectedfunctionresolve($abstract, $parameters = []){
// 获取别名对应的真实抽象类型
        $abstract = $this->getAlias($abstract);

// 如果已经有共享实例,直接返回
if (isset($this->instances[$abstract])) {
return$this->instances[$abstract];
        }

// 获取具体实现
        $concrete = $this->getConcrete($abstract);

// 构建实例
if ($this->isBuildable($concrete, $abstract)) {
            $object = $this->build($concrete, $parameters);
        } else {
// 递归解析
            $object = $this->make($concrete, $parameters);
        }

// 如果是共享的(单例),存储实例
if ($this->isShared($abstract)) {
$this->instances[$abstract] = $object;
        }

return $object;
    }

/**
     * 构建具体实例
     * 使用反射实现自动依赖注入
     */

publicfunctionbuild($concrete, array $parameters = []){
// 如果是闭包,直接执行
if ($concrete instanceof Closure) {
return $concrete($this, $parameters);
        }

// 使用反射获取类信息
        $reflector = new ReflectionClass($concrete);

// 检查类是否可实例化
if (!$reflector->isInstantiable()) {
thrownew BindingResolutionException(
"Target [$concrete] is not instantiable."
            );
        }

// 获取构造函数
        $constructor = $reflector->getConstructor();

// 如果没有构造函数,直接实例化
if (is_null($constructor)) {
returnnew $concrete;
        }

// 获取构造函数参数
        $dependencies = $constructor->getParameters();

// 解析所有依赖
        $instances = $this->resolveDependencies($dependencies, $parameters);

// 使用解析的依赖创建实例
return $reflector->newInstanceArgs($instances);
    }

/**
     * 解析依赖
     */

protectedfunctionresolveDependencies(array $dependencies, array $parameters){
        $results = [];

foreach ($dependencies as $dependency) {
// 如果参数已提供,使用提供的值
if (array_key_exists($dependency->getName(), $parameters)) {
                $results[] = $parameters[$dependency->getName()];
continue;
            }

// 获取参数类型
            $type = $dependency->getType();

// 如果是类类型,递归解析
if ($type && !$type->isBuiltin()) {
                $results[] = $this->make($type->getName());
            } elseif ($dependency->isDefaultValueAvailable()) {
// 使用默认值
                $results[] = $dependency->getDefaultValue();
            } else {
thrownew BindingResolutionException(
"Unresolvable dependency [{$dependency}]"
                );
            }
        }

return $results;
    }
}

2.2 依赖注入实战示例

<?php
/**
 * 理解Laravel依赖注入
 */


// 定义接口
interfacePaymentGateway{
publicfunctioncharge(float $amount)bool;
}

// 具体实现
classStripePaymentimplementsPaymentGateway{
publicfunctioncharge(float $amount)bool{
// Stripe支付逻辑
returntrue;
    }
}

classAlipayPaymentimplementsPaymentGateway{
publicfunctioncharge(float $amount)bool{
// 支付宝支付逻辑
returntrue;
    }
}

// 依赖PaymentGateway的服务
classOrderService{
private PaymentGateway $payment;
private LoggerInterface $logger;

// 构造函数注入
publicfunction__construct(PaymentGateway $payment, LoggerInterface $logger){
$this->payment = $payment;
$this->logger = $logger;
    }

publicfunctionprocessOrder(Order $order)bool{
$this->logger->info('Processing order: ' . $order->id);
return$this->payment->charge($order->total);
    }
}

// 在ServiceProvider中绑定
classAppServiceProviderextendsServiceProvider{
publicfunctionregister(){
// 绑定接口到具体实现
$this->app->bind(PaymentGateway::class, StripePayment::class);

// 或者使用闭包进行复杂绑定
$this->app->bind(PaymentGateway::class, function($app){
            $gateway = config('payment.gateway');

return match($gateway) {
'stripe' => new StripePayment(config('payment.stripe_key')),
'alipay' => new AlipayPayment(config('payment.alipay_key')),
default => thrownew InvalidArgumentException('Unknown gateway'),
            };
        });
    }
}

// 使用时,Laravel自动注入依赖
classOrderControllerextendsController{
publicfunctionstore(Request $request, OrderService $orderService){
// OrderService的依赖会被自动解析和注入
        $order = Order::create($request->validated());
        $orderService->processOrder($order);
    }
}

三、路由系统源码解析

3.1 Router核心实现

<?php
/**
 * Laravel路由核心源码解析
 * 文件位置:Illuminate/Routing/Router.php
 */


namespaceIlluminate\Routing;

classRouterimplementsRouterContract{

/**
     * 路由集合
     */

protected $routes;

/**
     * 容器实例
     */

protected $container;

/**
     * 当前路由组属性栈
     */

protected $groupStack = [];

/**
     * 注册GET路由
     */

publicfunctionget($uri, $action = null){
return$this->addRoute(['GET''HEAD'], $uri, $action);
    }

/**
     * 注册POST路由
     */

publicfunctionpost($uri, $action = null){
return$this->addRoute('POST', $uri, $action);
    }

/**
     * 添加路由到集合
     */

publicfunctionaddRoute($methods, $uri, $action){
return$this->routes->add(
$this->createRoute($methods, $uri, $action)
        );
    }

/**
     * 创建路由实例
     */

protectedfunctioncreateRoute($methods, $uri, $action){
// 如果action是控制器字符串,解析它
if ($this->actionReferencesController($action)) {
            $action = $this->convertToControllerAction($action);
        }

// 创建Route实例
        $route = $this->newRoute(
            $methods,
$this->prefix($uri),  // 添加前缀
            $action
        );

// 如果在路由组中,合并组属性
if ($this->hasGroupStack()) {
$this->mergeGroupAttributesIntoRoute($route);
        }

return $route;
    }

/**
     * 路由分组
     */

publicfunctiongroup(array $attributes, $routes){
// 将属性压入栈
$this->updateGroupStack($attributes);

// 加载路由
$this->loadRoutes($routes);

// 弹出属性
        array_pop($this->groupStack);
    }

/**
     * 分发请求到路由
     */

publicfunctiondispatch(Request $request){
return$this->dispatchToRoute($request);
    }

/**
     * 分发到匹配的路由
     */

publicfunctiondispatchToRoute(Request $request){
return$this->runRoute($request, $this->findRoute($request));
    }

/**
     * 查找匹配的路由
     */

protectedfunctionfindRoute($request){
// 从路由集合中匹配
        $route = $this->routes->match($request);

// 绑定路由到容器
$this->container->instance(Route::class, $route);

return $route;
    }

/**
     * 运行路由
     */

protectedfunctionrunRoute(Request $request, Route $route){
// 绑定请求到路由
        $request->setRouteResolver(fn() => $route);

// 通过管道运行中间件
return$this->prepareResponse(
            $request,
$this->runRouteWithinStack($route, $request)
        );
    }

/**
     * 在中间件栈中运行路由
     */

protectedfunctionrunRouteWithinStack(Route $route, Request $request){
// 获取路由中间件
        $middleware = $this->gatherRouteMiddleware($route);

// 使用Pipeline执行中间件
return (new Pipeline($this->container))
            ->send($request)
            ->through($middleware)
            ->then(fn($request) => $route->run());
    }
}

3.2 Route类解析

<?php
/**
 * Route类源码解析
 * 文件位置:Illuminate/Routing/Route.php
 */


namespaceIlluminate\Routing;

classRoute{

/**
     * HTTP方法
     */

public $methods;

/**
     * 路由URI
     */

public $uri;

/**
     * 路由动作
     */

public $action;

/**
     * 路由参数
     */

public $parameters = [];

/**
     * 参数名称
     */

public $parameterNames;

/**
     * 编译后的正则
     */

public $compiled;

/**
     * 运行路由动作
     */

publicfunctionrun(){
try {
if ($this->isControllerAction()) {
return$this->runController();
            }

return$this->runCallable();
        } catch (HttpResponseException $e) {
return $e->getResponse();
        }
    }

/**
     * 运行控制器动作
     */

protectedfunctionrunController(){
return$this->controllerDispatcher()->dispatch(
$this,
$this->getController(),
$this->getControllerMethod()
        );
    }

/**
     * 运行闭包动作
     */

protectedfunctionrunCallable(){
        $callable = $this->action['uses'];

// 解析闭包依赖并执行
return$this->container->call(
            $callable,
$this->parametersWithoutNulls()
        );
    }

/**
     * 匹配请求
     */

publicfunctionmatches(Request $request, $includingMethod = true){
// 编译路由
$this->compileRoute();

// 匹配URI
if (!preg_match($this->compiled->getRegex(), $request->path())) {
returnfalse;
        }

// 匹配HTTP方法
if ($includingMethod && !in_array($request->method(), $this->methods)) {
returnfalse;
        }

returntrue;
    }

/**
     * 绑定路由参数
     */

publicfunctionbind(Request $request){
// 从URI中提取参数
        preg_match($this->compiled->getRegex(), $request->path(), $matches);

// 绑定参数
$this->parameters = $this->matchToKeys(
            array_slice($matches, 1)
        );

return$this;
    }
}

// 路由使用示例
Route::get('/users/{id}', [UserController::class, 'show'])
    ->where('id''[0-9]+')
    ->middleware('auth');

Route::prefix('api')->group(function(){
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/users', [UserController::class, 'store']);
});

四、中间件Pipeline源码解析

4.1 Pipeline核心实现

<?php
/**
 * Pipeline管道源码解析
 * 文件位置:Illuminate/Pipeline/Pipeline.php
 * 
 * Pipeline是Laravel中间件的核心实现
 * 采用洋葱模型,请求从外到内,响应从内到外
 */


namespaceIlluminate\Pipeline;

classPipelineimplementsPipelineContract{

/**
     * 容器实例
     */

protected $container;

/**
     * 通过管道传递的对象
     */

protected $passable;

/**
     * 管道数组(中间件)
     */

protected $pipes = [];

/**
     * 每个管道调用的方法
     */

protected $method = 'handle';

/**
     * 设置通过管道的对象
     */

publicfunctionsend($passable){
$this->passable = $passable;
return$this;
    }

/**
     * 设置管道(中间件)
     */

publicfunctionthrough($pipes){
$this->pipes = is_array($pipes) ? $pipes : func_get_args();
return$this;
    }

/**
     * 设置调用方法
     */

publicfunctionvia($method){
$this->method = $method;
return$this;
    }

/**
     * 运行管道并返回结果
     * 这是Pipeline的核心方法
     */

publicfunctionthen(Closure $destination){
// 构建管道
        $pipeline = array_reduce(
// 反转管道顺序(实现洋葱模型)
            array_reverse($this->pipes()),
// 将每个管道包装成闭包
$this->carry(),
// 最终目的地(控制器动作)
$this->prepareDestination($destination)
        );

// 执行管道
return $pipeline($this->passable);
    }

/**
     * 获取闭包用于包装管道
     * 这是实现洋葱模型的关键
     */

protectedfunctioncarry(){
returnfunction($stack, $pipe){
returnfunction($passable)use($stack, $pipe){
try {
// 解析管道(中间件)
if (is_callable($pipe)) {
return $pipe($passable, $stack);
                    } elseif (!is_object($pipe)) {
// 字符串形式的中间件
                        [$name, $parameters] = $this->parsePipeString($pipe);
                        $pipe = $this->container->make($name);
                        $parameters = array_merge([$passable, $stack], $parameters);
                    } else {
                        $parameters = [$passable, $stack];
                    }

// 调用中间件的handle方法
return $pipe->{$this->method}(...$parameters);

                } catch (Throwable $e) {
return$this->handleException($passable, $e);
                }
            };
        };
    }

/**
     * 准备最终目的地闭包
     */

protectedfunctionprepareDestination(Closure $destination){
returnfunction($passable)use($destination){
return $destination($passable);
        };
    }
}

/**
 * 中间件执行流程图解
 * 
 * 请求 → Middleware1 → Middleware2 → Middleware3 → Controller
 *                                                      ↓
 * 响应 ← Middleware1 ← Middleware2 ← Middleware3 ← Response
 * 
 * 洋葱模型:
 * ┌─────────────────────────────────────────────────────┐
 * │ Middleware1 (before)                                │
 * │   ┌─────────────────────────────────────────────┐   │
 * │   │ Middleware2 (before)                        │   │
 * │   │   ┌─────────────────────────────────────┐   │   │
 * │   │   │ Middleware3 (before)                │   │   │
 * │   │   │   ┌─────────────────────────────┐   │   │   │
 * │   │   │   │      Controller Action      │   │   │   │
 * │   │   │   └─────────────────────────────┘   │   │   │
 * │   │   │ Middleware3 (after)                 │   │   │
 * │   │   └─────────────────────────────────────┘   │   │
 * │   │ Middleware2 (after)                         │   │
 * │   └─────────────────────────────────────────────┘   │
 * │ Middleware1 (after)                                 │
 * └─────────────────────────────────────────────────────┘
 */

4.2 中间件实现示例

<?php
/**
 * 自定义中间件示例
 */


namespaceApp\Http\Middleware;

useClosure;
useIlluminate\Http\Request;

classLogRequestMiddleware{

/**
     * 处理请求
     * 
     * @param Request $request 请求对象
     * @param Closure $next 下一个中间件
     */

publicfunctionhandle(Request $request, Closure $next){
// ========== 前置处理(请求进入时执行)==========
        $startTime = microtime(true);

        Log::info('Request started', [
'method' => $request->method(),
'url' => $request->fullUrl(),
'ip' => $request->ip(),
        ]);

// ========== 调用下一个中间件 ==========
        $response = $next($request);

// ========== 后置处理(响应返回时执行)==========
        $duration = round((microtime(true) - $startTime) * 10002);

        Log::info('Request completed', [
'status' => $response->getStatusCode(),
'duration' => $duration . 'ms',
        ]);

// 添加响应头
        $response->header('X-Response-Time', $duration . 'ms');

return $response;
    }
}

/**
 * 终止中间件
 * 在响应发送给客户端后执行
 */

classTerminatingMiddleware{

publicfunctionhandle(Request $request, Closure $next){
return $next($request);
    }

/**
     * 终止方法
     * 响应发送后执行,用于清理工作
     */

publicfunctionterminate(Request $request, $response){
// 记录慢请求
// 清理临时文件
// 发送统计数据
    }
}

/**
 * 带参数的中间件
 */

classRoleMiddleware{

publicfunctionhandle(Request $request, Closure $next, string $role){
if (!$request->user()->hasRole($role)) {
            abort(403'Unauthorized');
        }

return $next($request);
    }
}

// 使用:Route::get('/admin', ...)->middleware('role:admin');

五、Eloquent ORM源码解析

5.1 Model核心实现

<?php
/**
 * Eloquent Model源码解析
 * 文件位置:Illuminate/Database/Eloquent/Model.php
 */


namespaceIlluminate\Database\Eloquent;

abstractclassModelimplementsArrayableJsonable{

/**
     * 模型属性
     */

protected $attributes = [];

/**
     * 原始属性(用于脏检查)
     */

protected $original = [];

/**
     * 模型关联
     */

protected $relations = [];

/**
     * 表名
     */

protected $table;

/**
     * 主键
     */

protected $primaryKey = 'id';

/**
     * 可批量赋值的属性
     */

protected $fillable = [];

/**
     * 不可批量赋值的属性
     */

protected $guarded = ['*'];

/**
     * 创建新模型实例
     */

publicfunction__construct(array $attributes = []){
$this->syncOriginal();
$this->fill($attributes);
    }

/**
     * 批量赋值属性
     */

publicfunctionfill(array $attributes){
foreach ($this->fillableFromArray($attributes) as $key => $value) {
if ($this->isFillable($key)) {
$this->setAttribute($key, $value);
            }
        }

return$this;
    }

/**
     * 设置属性
     */

publicfunctionsetAttribute($key, $value){
// 检查是否有mutator(修改器)
if ($this->hasSetMutator($key)) {
return$this->setMutatedAttributeValue($key, $value);
        }

// 检查是否是日期属性
if ($value && $this->isDateAttribute($key)) {
            $value = $this->fromDateTime($value);
        }

// 检查是否需要类型转换
if ($this->hasCast($key)) {
            $value = $this->castAttribute($key, $value);
        }

$this->attributes[$key] = $value;

return$this;
    }

/**
     * 获取属性
     */

publicfunctiongetAttribute($key){
if (!$key) {
returnnull;
        }

// 从属性或关联中获取
if (array_key_exists($key, $this->attributes) ||
            array_key_exists($key, $this->casts) ||
$this->hasGetMutator($key)) {
return$this->getAttributeValue($key);
        }

// 检查是否是关联
if ($this->isRelation($key)) {
return$this->getRelationValue($key);
        }

returnnull;
    }

/**
     * 保存模型
     */

publicfunctionsave(array $options = []){
        $query = $this->newModelQuery();

// 判断是新建还是更新
if ($this->exists) {
            $saved = $this->isDirty() ? $this->performUpdate($query) : true;
        } else {
            $saved = $this->performInsert($query);
        }

if ($saved) {
$this->syncOriginal();
        }

return $saved;
    }

/**
     * 执行插入
     */

protectedfunctionperformInsert(Builder $query){
// 触发creating事件
if ($this->fireModelEvent('creating') === false) {
returnfalse;
        }

// 设置时间戳
if ($this->usesTimestamps()) {
$this->updateTimestamps();
        }

// 插入数据
        $attributes = $this->getAttributes();

if ($this->getIncrementing()) {
$this->insertAndSetId($query, $attributes);
        } else {
            $query->insert($attributes);
        }

$this->exists = true;

// 触发created事件
$this->fireModelEvent('created'false);

returntrue;
    }

/**
     * 执行更新
     */

protectedfunctionperformUpdate(Builder $query){
// 触发updating事件
if ($this->fireModelEvent('updating') === false) {
returnfalse;
        }

// 更新时间戳
if ($this->usesTimestamps()) {
$this->updateTimestamps();
        }

// 只更新脏数据
        $dirty = $this->getDirty();

if (count($dirty) > 0) {
            $query->where($this->getKeyName(), $this->getKey())
                  ->update($dirty);

$this->syncChanges();

// 触发updated事件
$this->fireModelEvent('updated'false);
        }

returntrue;
    }

/**
     * 检查属性是否被修改
     */

publicfunctionisDirty($attributes = null){
return$this->hasChanges(
$this->getDirty(), is_array($attributes) ? $attributes : func_get_args()
        );
    }

/**
     * 获取修改的属性
     */

publicfunctiongetDirty(){
        $dirty = [];

foreach ($this->getAttributes() as $key => $value) {
if (!$this->originalIsEquivalent($key)) {
                $dirty[$key] = $value;
            }
        }

return $dirty;
    }

/**
     * 魔术方法:获取属性
     */

publicfunction__get($key){
return$this->getAttribute($key);
    }

/**
     * 魔术方法:设置属性
     */

publicfunction__set($key, $value){
$this->setAttribute($key, $value);
    }

/**
     * 静态方法调用转发到查询构建器
     */

publicstaticfunction__callStatic($method, $parameters){
return (newstatic)->$method(...$parameters);
    }
}

5.2 关联关系实现

<?php
/**
 * Eloquent关联关系源码解析
 */


// HasMany关联
classHasManyextendsHasOneOrMany{

publicfunctiongetResults(){
return$this->query->get();
    }
}

// BelongsTo关联
classBelongsToextendsRelation{

protected $foreignKey;
protected $ownerKey;

publicfunctiongetResults(){
if (is_null($this->child->{$this->foreignKey})) {
return$this->getDefaultFor($this->parent);
        }

return$this->query->first();
    }

publicfunctionaddConstraints(){
        $table = $this->related->getTable();

$this->query->where(
            $table.'.'.$this->ownerKey,
'=',
$this->child->{$this->foreignKey}
        );
    }
}

// 使用示例
classUserextendsModel{

// 一对多
publicfunctionposts(){
return$this->hasMany(Post::class);
    }

// 多对多
publicfunctionroles(){
return$this->belongsToMany(Role::class);
    }
}

classPostextendsModel{

// 反向关联
publicfunctionuser(){
return$this->belongsTo(User::class);
    }
}

// 预加载解决N+1问题
$users = User::with('posts')->get();

// 懒加载
$user = User::find(1);
$posts = $user->posts;  // 触发查询

六、Facade门面源码解析

6.1 Facade核心实现

<?php
/**
 * Facade门面源码解析
 * 文件位置:Illuminate/Support/Facades/Facade.php
 * 
 * Facade提供了一种静态接口来访问容器中的服务
 * 本质是代理模式的实现
 */


namespaceIlluminate\Support\Facades;

abstractclassFacade{

/**
     * 应用实例
     */

protectedstatic $app;

/**
     * 已解析的对象实例
     */

protectedstatic $resolvedInstance = [];

/**
     * 获取Facade背后的服务名称
     * 子类必须实现此方法
     */

protectedstaticfunctiongetFacadeAccessor(){
thrownew RuntimeException('Facade does not implement getFacadeAccessor method.');
    }

/**
     * 解析Facade背后的实例
     */

protectedstaticfunctionresolveFacadeInstance($name){
// 如果已经是对象,直接返回
if (is_object($name)) {
return $name;
        }

// 检查是否已解析
if (isset(static::$resolvedInstance[$name])) {
returnstatic::$resolvedInstance[$name];
        }

// 从容器解析
if (static::$app) {
returnstatic::$resolvedInstance[$name] = static::$app[$name];
        }
    }

/**
     * 获取Facade根对象
     */

publicstaticfunctiongetFacadeRoot(){
returnstatic::resolveFacadeInstance(static::getFacadeAccessor());
    }

/**
     * 魔术方法:处理静态调用
     * 这是Facade的核心
     */

publicstaticfunction__callStatic($method, $args){
// 获取实际的服务实例
        $instance = static::getFacadeRoot();

if (!$instance) {
thrownew RuntimeException('A facade root has not been set.');
        }

// 调用实例方法
return $instance->$method(...$args);
    }
}

/**
 * Cache Facade示例
 */

classCacheextendsFacade{

protectedstaticfunctiongetFacadeAccessor(){
return'cache';  // 返回容器中的服务名称
    }
}

/**
 * 调用流程解析
 * 
 * Cache::get('key')
 *    ↓
 * Facade::__callStatic('get', ['key'])
 *    ↓
 * static::getFacadeRoot()
 *    ↓
 * static::resolveFacadeInstance('cache')
 *    ↓
 * $app['cache']  // 从容器获取CacheManager实例
 *    ↓
 * $instance->get('key')  // 调用实际方法
 */

6.2 常用Facade对照表

<?php
/**
 * Laravel常用Facade对照表
 */


/*
┌─────────────────┬─────────────────────┬─────────────────────────────────┐
│    Facade       │   服务容器绑定        │         实际类                   │
├─────────────────┼─────────────────────┼─────────────────────────────────┤
│ App             │ app                 │ Application                     │
│ Auth            │ auth                │ AuthManager                     │
│ Cache           │ cache               │ CacheManager                    │
│ Config          │ config              │ Repository                      │
│ DB              │ db                  │ DatabaseManager                 │
│ Event           │ events              │ Dispatcher                      │
│ File            │ files               │ Filesystem                      │
│ Hash            │ hash                │ HashManager                     │
│ Log             │ log                 │ LogManager                      │
│ Mail            │ mailer              │ Mailer                          │
│ Queue           │ queue               │ QueueManager                    │
│ Redis           │ redis               │ RedisManager                    │
│ Request         │ request             │ Request                         │
│ Response        │ (闭包)              │ ResponseFactory                 │
│ Route           │ router              │ Router                          │
│ Session         │ session             │ SessionManager                  │
│ Storage         │ filesystem          │ FilesystemManager               │
│ Validator       │ validator           │ Factory                         │
│ View            │ view                │ Factory                         │
└─────────────────┴─────────────────────┴─────────────────────────────────┘
*/


// Facade vs 依赖注入
// Facade方式
Cache::put('key''value'60);
$value = Cache::get('key');

// 依赖注入方式(推荐用于测试)
classUserService{
publicfunction__construct(
        private CacheManager $cache
    )
{}

publicfunctiongetUser(int $id){
return$this->cache->remember("user:{$id}"60function()use($id){
return User::find($id);
        });
    }
}

七、事件系统源码解析

7.1 Dispatcher核心实现

<?php
/**
 * 事件调度器源码解析
 * 文件位置:Illuminate/Events/Dispatcher.php
 */


namespaceIlluminate\Events;

classDispatcherimplementsDispatcherContract{

/**
     * 注册的监听器
     */

protected $listeners = [];

/**
     * 通配符监听器
     */

protected $wildcards = [];

/**
     * 注册事件监听器
     */

publicfunctionlisten($events, $listener = null){
if ($events instanceof Closure) {
// 自动发现事件类型
return$this->listen($this->firstClosureParameterType($events), $events);
        }

foreach ((array) $events as $event) {
if (str_contains($event, '*')) {
// 通配符监听
$this->setupWildcardListen($event, $listener);
            } else {
// 普通监听
$this->listeners[$event][] = $this->makeListener($listener);
            }
        }
    }

/**
     * 触发事件
     */

publicfunctiondispatch($event, $payload = [], $halt = false){
// 获取事件名称和payload
        [$event, $payload] = $this->parseEventAndPayload($event, $payload);

// 获取所有监听器
        $listeners = $this->getListeners($event);

        $responses = [];

foreach ($listeners as $listener) {
            $response = $listener($event, $payload);

// 如果halt为true且有返回值,停止传播
if ($halt && !is_null($response)) {
return $response;
            }

// 如果返回false,停止传播
if ($response === false) {
break;
            }

            $responses[] = $response;
        }

return $halt ? null : $responses;
    }

/**
     * 获取事件的所有监听器
     */

publicfunctiongetListeners($eventName){
        $listeners = $this->listeners[$eventName] ?? [];

// 合并通配符监听器
        $listeners = array_merge(
            $listeners,
$this->getWildcardListeners($eventName)
        );

// 检查事件类是否有监听器
return class_exists($eventName, false)
            ? $this->addInterfaceListeners($eventName, $listeners)
            : $listeners;
    }

/**
     * 创建监听器闭包
     */

protectedfunctionmakeListener($listener, $wildcard = false){
if (is_string($listener)) {
// 字符串形式:'App\Listeners\UserListener@handle'
return$this->createClassListener($listener, $wildcard);
        }

if (is_array($listener) && isset($listener[0]) && is_string($listener[0])) {
// 数组形式:[UserListener::class, 'handle']
return$this->createClassListener($listener, $wildcard);
        }

// 闭包形式
returnfunction($event, $payload)use($listener, $wildcard){
if ($wildcard) {
return $listener($event, $payload);
            }

return $listener(...array_values($payload));
        };
    }
}

// 使用示例
// 定义事件
classUserRegistered{
publicfunction__construct(
        public User $user
    )
{}
}

// 定义监听器
classSendWelcomeEmail{
publicfunctionhandle(UserRegistered $event){
        Mail::to($event->user->email)->send(new WelcomeEmail($event->user));
    }
}

// 注册监听器
Event::listen(UserRegistered::class, SendWelcomeEmail::class);

// 触发事件
event(new UserRegistered($user));
// 或
Event::dispatch(new UserRegistered($user));

八、总结

8.1 Laravel设计模式总结

【Laravel使用的设计模式】

1、服务容器 - IoC/依赖注入
   - 解耦组件依赖
   - 便于测试和替换

2、Facade - 代理模式
   - 提供简洁的静态接口
   - 隐藏复杂的实现细节

3、Pipeline - 责任链模式
   - 中间件实现
   - 请求/响应处理链

4、Observer - 观察者模式
   - 事件系统
   - Model事件

5、Factory - 工厂模式
   - 各种Manager类
   - 创建复杂对象

6、Repository - 仓储模式
   - Eloquent ORM
   - 数据访问抽象

7、Strategy - 策略模式
   - 缓存驱动
   - 队列驱动
   - 认证守卫

8.2 学习建议

【Laravel源码学习路径】

入门级:
├── 1、理解服务容器和依赖注入
├── 2、学习Facade的实现原理
└── 3、掌握中间件Pipeline

进阶级:
├── 4、深入Eloquent ORM
├── 5、理解事件系统
└── 6、学习队列实现

高级:
├── 7、研究路由编译和匹配
├── 8、分析请求生命周期
└── 9、理解服务提供者启动流程

📌 下期预告:《ThinkPHP核心源码解读》

本站文章均为手工撰写未经允许谢绝转载:夜雨聆风 » Laravel核心源码解读

猜你喜欢

  • 暂无文章