mercredi 23 septembre 2015

Create a object with depenencies that have to be configured

I am creating a client using GuzzleHttp 5.3. I want use the same Config object to configure the Guzzle Client. So, the creation of Guzzle Client depends of the object Config.

For example:

$config = new Config([
    'user' => 'github',
    'password' => '1234',
    'base_url' => 'http://ift.tt/1Ptwlr5'
]);

new GithubClient($config, new \GuzzleHttp\Client());

And the constructor:

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.
}

But, I have to inject the Guzzle Client because I have to do unit tests.

One option is to inject a Guzzle Client configured as my client requires it. But the build process is a little cumbersome (set base_url, default header). The user must to know using Guzzle, I do not like this.

Other option is to create a new object (GithubClientFactory for example) to create my client.

$client = GithubClientFactory::make($config);

So, I hide the Guzzle dependency and the setup process. But the user always have to use the client factory.

Then, Is there a better (pattern) design to this problem?

Aucun commentaire:

Enregistrer un commentaire