Injecting single-use object into class

Posted by moteutsch on Stack Overflow See other posts from Stack Overflow or by moteutsch
Published on 2012-10-16T16:56:02Z Indexed on 2012/10/22 17:01 UTC
Read the original article Hit count: 144

Filed under:
|

I have the following code:

<?php

class X
{
    public function do($url)
    {
        $httpRequest = new \HttpRequest\Curl($url, $this->getOptions());
        $httpRequest->fire();
        // etc.
    }
    // ...
}

In order to be able to unit test this class, I'd like to inject a mocked HttpRequest class. One way to do this would be as follows:

<?php

class X
{
    private $httpRequestClass;

    public function __construct($httpRequestClass = '\HttpRequest\Curl')
    {
        $this->httpRequestClass = $httpRequestClass;
    }

    public function do($url)
    {
        $httpRequest = new $this->httpRequestClass($url, $this->getOptions());
        $httpRequest->fire();
        // etc.
    }
    // ...
}

But this doesn't seem right. Any other ideas?

© Stack Overflow or respective owner

Related posts about php

Related posts about dependency-injection