1

I'm using the Zend HTTP client to implement a web client for communicating with a third-party service. I was thinking about making it a singleton pattern so each call could take advantage of using cookies from the service, so that we wouldn't need to re-login every time we instantiate a new version of the client.

The client will have multiple classes communicating with it, possibly from several different locations in code trying all at once. I'm worried that having a singleton client will cause race conditions when multiple entities try to use it at once.

Will this be an issue with the singleton pattern in a PHP HTTP client? If so, is there any other way to have the benefit of a Zend HTTP client that can store and use cookies across multiple transactions without having these issues?

dsw88
  • 4,400
  • 8
  • 37
  • 50
  • It's PHP... you'd be instantiating a client on every request to your app anyways. Store the login cookies from this 3rd party service in a session variable, and it'll be available for every instance of your app for re-use. – Marc B Sep 28 '12 at 16:25
  • ' I was thinking about making it a singleton pattern so each call could take advantage of using cookies from the service, so that we wouldn't need to re-login every time we instantiate a new version of the client' :::: what does that even mean???? i guess u got completely wrong what singleton pattern is .... – Surace Sep 28 '12 at 16:27
  • @Surace Telling me I'm an idiot really doesn't help anyone. I know what a singleton pattern is, you only have one instance of a given class. So for a Zend HTTP client, the cookie jar used by the client will have all the cookies from the sources that client connects to. If you re-instantiated an instance of the class every time you used the HTTP client (i.e. not using the singleton pattern), it will create a new, empty cookie jar containing none of the cookies from previous clients you'd like to keep around. – dsw88 Sep 28 '12 at 16:40
  • @Marc B - It's an API, so sometimes a given API function will make multiple calls to these third-party services on a single request to my app. Thanks for the suggestion, I'll look into possibly storing the cookie in a session variable. – dsw88 Sep 28 '12 at 16:42

1 Answers1

0

Since PHP is not multithreaded, this alone shouldn't be able to cause a race condition.

It would be possible if there are multiple requests at the same time and you're using a shared resource (e.g. a file on your server). In that case you would need to have proper locking in place, such as flock().

You could also store cookies per session, i.e. shared-nothing architecture; that should solve the problem as well.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309