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.

1
  • Modified the example so the client is created in the constructor instead of lazy loading it. Commented Jan 21, 2011 at 20:53

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
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: stackoverflow.com/questions/1005473/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.