# provider **Repository Path**: fiberphp/provider ## Basic Information - **Project Name**: provider - **Description**: FiberPHP 服务提供者基类 —— register/boot/bootAfter 生命周期钩子、critical/network/bootTimeout 调度元数据、singleton 便捷绑定。 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-18 - **Last Updated**: 2026-11-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # FiberPHP Provider 服务提供者基类:`register()` / `boot()` 生命周期钩子、`bootAfter()` 启动顺序声明与 critical / network / bootTimeout 调度元数据。 ## 环境要求 - PHP >= 8.5 - fiberphp/config - fiberphp/container - psr/log ^3.0 ## 安装 ```bash composer require fiberphp/provider ``` ## 快速上手 ```php 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` 数组: ```php return [ 'providers' => [ App\Provider\DemoProvider::class, ], ]; ``` ## 生命周期 | 方法 | 阶段 | 说明 | |---|---|---| | `register(): void` | 容器注册 | 绑定服务、读取配置;默认空实现,按需覆盖 | | `boot(?object $worker = null): void` | 启动 | `$worker` 为当前 Worker 实例,CLI 场景可能为 `null`;默认空实现,按需覆盖 | 两个钩子都可省略;子类只覆盖需要的阶段即可。 ## 启动顺序 `bootAfter()` 声明必须先完成 boot 的 Provider 类名: ```php public static function bootAfter(): array { return [FooProvider::class]; // FooProvider 必须先完成 boot } ``` 返回值为 `list`;未出现在 Provider 列表中的类会被忽略。 ## 调度元数据 子类通过三个受保护属性声明启动策略,`bootMeta()` 返回其汇总: | 属性 | 说明 | 默认值 | |---|---|---| | `$critical` | boot 失败时是否终止启动:`true` 抛出异常,`false` 记录 warning 后跳过该 Provider | `false` | | `$network` | boot 是否可能发起网络建连;为 `true` 时配合正数 `$bootTimeout` 启用超时保护 | `false` | | `$bootTimeout` | boot 超时秒数;`null` 或 `0` 表示不启用 | `null` | ```php 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` | 绑定单例,并把其余键作为别名指向同一实例 | ```php use FiberPHP\Container\Container; use Psr\Log\LoggerInterface; $this->singleton( DemoService::class, static fn (Container $c) => new DemoService($c->get(LoggerInterface::class)), DemoServiceInterface::class, ); ``` ## 测试 ```bash composer test ``` ## 与其它包的关系 - 各组件的 Provider(`fiberphp/http`、`fiberphp/router`、`fiberphp/log` 等)继承本包基类。 - `fiberphp/framework` 负责两阶段调度:先全部 `register()`,再按 `bootAfter()` 拓扑排序执行 `boot()`。 - 绑定经 `fiberphp/container`,配置经 `fiberphp/config`。 ## License MIT