Php 创建具有必须配置的从属关系的对象
我正在使用HTTP 5.3创建一个客户端。我想使用相同的Php 创建具有必须配置的从属关系的对象,php,design-patterns,client,Php,Design Patterns,Client,我正在使用HTTP 5.3创建一个客户端。我想使用相同的Config对象来配置Guzzle客户端。因此,Guzzle客户端的创建取决于对象Config 例如: $config = new Config([ 'user' => 'github', 'password' => '1234', 'base_url' => 'http://test_or_production_url.com' ]); new GithubClient($config, new
Config
对象来配置Guzzle客户端。因此,Guzzle客户端的创建取决于对象Config
例如:
$config = new Config([
'user' => 'github',
'password' => '1234',
'base_url' => 'http://test_or_production_url.com'
]);
new GithubClient($config, new \GuzzleHttp\Client());
建造商:
public function __construct(Config $config)
{
$this->authData = [
'uname' => $config->getUser(),
'upassword' => $config->getPassword(),
];
$this->config = $config;
$this->httpClient = new \GuzzleHttp\Client(['base_url' => $config->getBaseUrl());
// I have to setup default headers, too.
}
但是,我必须注入Guzzle客户端,因为我必须进行单元测试
一个选项是注入一个配置为我的客户机所需的Guzzle客户机。但是构建过程有点麻烦(set base_url,默认头)。用户必须知道如何使用Guzzle,我不喜欢这样
另一个选项是创建一个新对象(GithubClientFactory
)来创建我的客户机
$client = GithubClientFactory::make($config);
因此,我隐藏了Guzzle依赖项和设置过程。但是用户始终必须使用客户端工厂
那么,对于这个问题有更好的(模式)设计吗