guzzle / guzzle

Guzzle, an extensible PHP HTTP client

Home Page:https://docs.guzzlephp.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom Global Default Config

khepin opened this issue · comments

Description
I'm trying to gauge if there would be much interest from the maintainers and or the community in enabling more global default configs.

Currently the global defaults are set in the Client and some of those can be configured globally by the users while others can't.

  • The PROXY related configs can all be set via environment variables
  • The redirect configs are all on a public static property and can therefore also be globally configured as defaults by the user.
  • Everything else is unreachable

Example: User-Agent
In our specific case, what we're trying to do is to get a default user agent for each service. The UA header is usually captured in traces and logs and can be invaluable when debugging and tracking issues.

Working on larger / older systems, there are many places where new Guzzle clients are created without being given a specific configs. Some of those can be very non-trivial to identify.

Sometimes, the client is created in a library that is not in the control of the app maintainers. This means many of those older apps all introduce themselves as GuzzleHttp/7 by default.

Since finding and updating all the places where a Guzzle client is being created isn't practical, we're looking for approaches that would allow setting a default within a given app that would differ from GuzzleHttp/7.

What could this look like

The configuration that is currently done via env vars is done so for historical reason and it doesn't seem reasonable to pursue that as the mechanism for more flexibility in global configuration.

So it would probably look like

\GuzzleHttp\Client::setDefaultConfig($config); // with a config array / object
// or
\GuzzleHttp\Client::setDefaultConfig($key, $value);
\GuzzleHttp\Client::setDefaultConfig('headers.User-Agent', env('HTTP_USER_AGENT'));
// or
\GuzzleHttp\Client::$defaults = $config;

Or something else.

What next

If there is interest from the maintainers / community in enabling something like this, I'd be happy to start working on a PR for it.

Thanks for getting in touch. My feeling is that this static global state is a bad practice, and I'm not particularly interested in perusing this in the library core. Frameworks like Laravel have a way of providing syntax that looks like that, but is actually not that, which could be a way to achive what you want with configuring defaults, or making a factory class. I indeed have such a package https://github.com/grahamCampbell/guzzle-factory. ;)

I agree the pointers you give work fine for building things moving forward.

I don't think they work as well when you're trying to update things for a large existing code base with disparate usage of Guzzle clients. Or am I missing something?