不能在工厂构造函数中获取Request,必须延迟到方法调用时通过Context::get(ServerRequestInterface::class)动态解析;因Container是进程级共享而Context是协程级隔离,构造阶段上下文未建立,需每次调用前resolve以保证多协程安全。

Hyperf中工厂方法里拿不到Request怎么办
在 Container 的工厂回调中直接调用 $container->get(Request::class) 会报错:Entry "Hyperf\HttpMessage\Server\Request" cannot be resolved: Entry "Psr\Http\Message\ServerRequestInterface" cannot be resolved。这是因为容器构建阶段 Request 尚未注入,工厂执行时上下文还未建立。
正确做法是延迟解析,把真正依赖 Request 的逻辑推迟到服务被实际调用时再获取。常见手段有:
- 工厂返回一个闭包或代理对象,在首次调用其方法时才从
ApplicationContext中取Request - 使用
Container::make()替代get(),但仅限当前请求生命周期内(需确保调用发生在中间件/控制器之后) - 改用
Context::get()—— 它比容器更轻量,且在请求生命周期中已预设好ServerRequestInterface实例
如何在工厂里根据Header动态切换服务实例
核心思路是:工厂不直接 new 实例,而是返回一个“策略型代理”,它在每次方法调用前检查当前请求的 Header,再决定用哪个具体实现。
示例场景:按 X-Client-Type: mobile/web 返回不同缓存客户端:
$container->set(CacheClientInterface::class, function (ContainerInterface $container) {
return new class($container) implements CacheClientInterface {
private ContainerInterface $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
private function resolve(): CacheClientInterface
{
$request = Context::get(ServerRequestInterface::class);
$clientType = $request->getHeaderLine('X-Client-Type');
return match ($clientType) {
'mobile' => $this->container->get(MobileCacheClient::class),
'web' => $this->container->get(WebCacheClient::class),
default => $this->container->get(DefaultCacheClient::class),
};
}
public function get(string $key): mixed
{
return $this->resolve()->get($key);
}
public function set(string $key, mixed $value, ?int $ttl = null): bool
{
return $this->resolve()->set($key, $value, $ttl);
}
};
});
注意:Context::get() 是安全的,只要该代码运行在请求生命周期内(如控制器、命令行命令中不行);若在协程启动前或非 HTTP 上下文中调用,会返回 null。
为什么不能在__construct里解析Header
因为服务实例化可能发生在请求到达前(比如在 onWorkerStart 阶段就被提前初始化),此时 Context 还没写入当前协程的上下文池,Context::get() 必然失败。即使强行用 $container->get(Request::class),也会触发容器循环依赖或未初始化异常。
所以必须把 Header 解析时机卡在“第一次业务调用”时刻,而不是“服务构建”时刻。这也是为什么上面示例中所有方法都先调用 resolve(),而不是在构造函数里做判断。
- 构造函数只保存
$container,不做任何上下文读取 - 每个公共方法入口都是解析点,天然适配多协程并发(每个协程有自己的
Context) - 如果性能敏感,可加属性缓存本次解析结果(但要注意协程隔离,不能用静态变量)
替换默认服务时要注意容器覆盖规则
如果你在 dependencies.php 中定义了 CacheClientInterface::class 的绑定,又在 beforeMainServerStart 或其他地方重复 $container->set(),后者会覆盖前者。但要注意:
-
set()是运行时覆盖,只影响后续get()调用,不影响已创建的单例实例 - 若原服务是
singleton模式,且已被其他服务提前引用过,则你的新工厂不会生效 - 推荐统一在
dependencies.php中注册,避免分散管理;若需动态行为,就按上文方式返回代理对象
最易被忽略的一点:Hyperf 的 Context 是协程级隔离的,但 Container 是进程级共享的。所有基于 Context 的决策都天然支持多请求并发,但别试图在工厂里缓存 Request 实例到属性里——它会在下一个协程里复用,导致 Header 错乱。


















