0

I'm considering my options for setting up a class for unit testing. This particular class should ALWAYS use the same soap client configuration under normal circumstances. I feel like users of the class shouldn't need to be concerned with setting up a soap client when they use it. Or, even be aware that it uses soap at all.

Really the only exception is in unit testing. I'll need to be able to mock the Soap_Client. I've come up with the following approach where i create the soap client in the constructor and can optionally set it with setSoapClient().

class WebServiceLayer
{
    const WSDL_URL = 'https://www.example.com/?WSDL';

    private $soapClient;

    public function __construct()
    {
        $this->soapClient = new Soap_Client(self::WSDL_URL);
    }

    public function setSoapClient(Soap_Client $soapClient)
    {
        $this->soapClient = $soapClient;
    }

    public function fetchSomeResponse()
    {
        $soapClient = $this->soapClient;
        return $soapClient->someRequest();
    }
}

Is this a valid way to handle this? The only problem i see with it, is that im instantiating the client in the constructor which "i've heard" is something to avoid.

I've run into this dilemma before on other classes, so it would be really nice to get peoples opinions on this.

AaronSzy
  • 728
  • 1
  • 6
  • 11

1 Answers1

2

Looks fine to me... you're using standard Setter injection. The only strange thing is returning a new client in the Getter. Why not return null if it hasn't been injected?

sourcenouveau
  • 29,356
  • 35
  • 146
  • 243
  • I'm having the getter create a soap client with the typical configuration. However, now that i look at it i might as well just create it in the constructor instead. It's simpler. – AaronSzy Jan 21 '11 at 20:49
  • 1
    Having WebServiceLayer instantiate the SOAP client kind of defeats the purpose of dependency injection... if you really want loosely-coupled code, even your default value should be injected. – sourcenouveau Jan 21 '11 at 21:06
  • Ya that makes sense. I was thinking that knowledge of HOW it works shouldn't need to be a concern for a user of the class. But i guess thats kind-of a trade off you have to make to get loose coupling. I think this question addresses my root concern: http://stackoverflow.com/questions/1005473/must-dependency-injection-come-at-the-expense-of-encapsulation – AaronSzy Jan 21 '11 at 21:12