Search by

fiberphp / provider

fiberphp

FiberPHP 服务提供者基类 —— register/boot/bootAfter 生命周期钩子、critical/network/bootTimeout 调度元数据、singleton 便捷绑定。

v0.1.0 2026-11-22 11:09 UTC

This package is auto-updated.

Last update: 2026-11-22 11:11:04 UTC


README

服务提供者基类:register() / boot() 生命周期钩子、bootAfter() 启动顺序声明与 critical / network / bootTimeout 调度元数据。

环境要求

  • PHP >= 8.5
  • fiberphp/config
  • fiberphp/container
  • psr/log ^3.0

安装

composer require fiberphp/provider

快速上手

namespace App\Provider;

use FiberPHP\Provider\ServiceProvider;

final class DemoProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->singleton(DemoService::class);
    }

    public function boot(?object $worker = null): void
    {
        $this->logger()->info('demo provider booted');
    }
}

FiberPHP 应用中把 Provider 类名加入 config/app.php 的 providers 数组:

return [
    'providers' => [
        App\Provider\DemoProvider::class,
    ],
];

生命周期

方法阶段说明
register(): void容器注册绑定服务、读取配置;默认空实现,按需覆盖
boot(?object $worker = null): void启动$worker 为当前 Worker 实例,CLI 场景可能为 null;默认空实现,按需覆盖

两个钩子都可省略;子类只覆盖需要的阶段即可。

启动顺序

bootAfter() 声明必须先完成 boot 的 Provider 类名:

public static function bootAfter(): array
{
    return [FooProvider::class];  // FooProvider 必须先完成 boot
}

返回值为 list<class-string>;未出现在 Provider 列表中的类会被忽略。

调度元数据

子类通过三个受保护属性声明启动策略,bootMeta() 返回其汇总:

属性说明默认值
$criticalboot 失败时是否终止启动:true 抛出异常,false 记录 warning 后跳过该 Providerfalse
$networkboot 是否可能发起网络建连;为 true 时配合正数 $bootTimeout 启用超时保护false
$bootTimeoutboot 超时秒数;null 或 0 表示不启用null
protected bool $critical = true;
protected bool $network = true;
protected int|float|null $bootTimeout = 5;

// bootMeta() 返回 ['critical' => true, 'network' => true, 'timeout' => 5]

便捷方法

方法说明
$this->container(): Container获取全局容器 Container::getInstance()
$this->logger(): LoggerInterface获取容器中的 LoggerInterface(未绑定时回退 NullLogger)
$this->singleton(string $concrete, object\|string\|null $factory = null, string ...$keys): void绑定单例,并把其余键作为别名指向同一实例
use FiberPHP\Container\Container;
use Psr\Log\LoggerInterface;

$this->singleton(
    DemoService::class,
    static fn (Container $c) => new DemoService($c->get(LoggerInterface::class)),
    DemoServiceInterface::class,
);

测试

composer test

与其它包的关系

  • 各组件的 Provider(fiberphp/http、fiberphp/router、fiberphp/log 等)继承本包基类。
  • fiberphp/framework 负责两阶段调度:先全部 register(),再按 bootAfter() 拓扑排序执行 boot()。
  • 绑定经 fiberphp/container,配置经 fiberphp/config。

License

MIT