gpt4 book ai didi

guzzle - 将额外参数传递给 eightpoints/guzzle 客户端类 (Symfony 4)

转载 作者:行者123 更新时间:2023-12-05 07:28:20 25 4
gpt4 key购买 nike

在 Symfony 4 项目中,我使用 eightpoints/guzzle 包来调用远程 API。安装 bundle (并在单独的 yaml 文件中配置客户端)后,我关注了 this quide让我的客户 Autowiring ,效果很好。然后使用一些更高级别的方法扩展我的客户端类(即从 GuzzleHttp\Client 派生的类,相当于上述指南中的 ApiPaymentClient 类)照顾我需要的电话,这也很好用。

问题是:有没有办法让我的客户类接受额外的参数?具体来说,我想在 services.yamlparameters 部分定义一个参数,然后将其绑定(bind)到客户端类构造函数中的特定额外参数(它将然后将参数值存储在私有(private)变量中以便在方法中使用),即

class MyClient extends GuzzleHttp\Client
{
public function __construct($config, $apiKey)
{
parent::__construct($config);
$this->apiKey = $apiKey;
}
/*...*/
}

最初(即作为上述指南的结果)services.yaml 中客户端服务的定义如下:

App\Client\MyClient: '@eight_points_guzzle.client.my_client'

这确保 MyClient 获得在

中定义的配置
eight_points_guzzle:
clients:
my_client:

单独的捆绑配置文件中的部分 (eight_points_guzzle.yaml)。

如何更改 App\Client\MyClient 服务定义以接受额外参数并仍然从 eight_points_guzzle.yaml 获取配置?到目前为止,我已经管理了一个或另一个工作,但不是两个(即,使绑定(bind)工作使得来自 eight_points_guzzle.yaml 的客户端定义不被读取,反之亦然。)

底线:是的,我可以在 MyClient 类中将参数定义为类 const,但我不喜欢这种解决方案;更不用说我有一天需要传递服务的情况,而不仅仅是一个简单的变量。

最佳答案

我找到的解决方案不是扩展 GuzzleHttp\Client 而是将其作为依赖项注入(inject)到另一个服务 - 包装器中并使用该包装器服务。所以你需要两种服务而不是一种。第一个是扩展的 Guzzle 客户端配置如下:

eight_points_guzzle:
clients:
extended_guzzle:
/*...*/

第二个是:

class MyClientWrapper
{
public function __construct(
ClientInterface $extendedGuzzleClient,
$apiKey
) {
$this->extendedGuzzleClient = $extendedGuzzleClient;
$this->apiKey = $apiKey;
}

public function request()
{
/*...*/
return $this->extendedGuzzleClient->request();
}
/*...*/
}

然后你就可以使用它了:

/*...*/
$this->myClientWrapper->request();
/*...*/

顺便说一句,如果你将你的 guzzle 客户端命名为 extended_guzzle 那么你可以将它注入(inject)到你的包装器服务中,比如 ClientInterface $extendedGuzzleClient Autowiring 将自动连接你的服务通过命名。

关于guzzle - 将额外参数传递给 eightpoints/guzzle 客户端类 (Symfony 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com