ResponseFactory and content negotiation
GT\Http\ResponseFactory creates a response object based on the request’s Accept header.
This is useful when one application can return different response types depending on what the client asked for.
The basic idea
Before the factory can build anything, you register which response class should handle which media type.
use GT\Http\Response;
use GT\Http\ResponseFactory;
ResponseFactory::registerResponseClass(Response::class, "text/html");
Then call create() with a request:
$response = ResponseFactory::create($request);
Why registration is required
The factory does not guess which class to use. It only uses classes that you have explicitly mapped.
If you call create() before registering a matching response class, it throws UnknownAcceptHeaderException.
That behaviour is intentional. It avoids silently creating the wrong response type.
Default accept type
If you register a response class without any media types, the factory uses its default accept type:
ResponseFactory::registerResponseClass(MyHtmlResponse::class);
That default is text/html.
Negotiation
Internally, the factory uses content negotiation to compare the incoming Accept header against a small set of priorities:
text/html; charset=UTF-8application/jsonapplication/xml;q=0.5
The winning media type is then used to look up the registered response class.
A simple example
use GT\Http\Request;
use GT\Http\Response;
use GT\Http\ResponseFactory;
class HtmlResponse extends Response {}
class JsonResponse extends Response {}
ResponseFactory::registerResponseClass(HtmlResponse::class, "text/html");
ResponseFactory::registerResponseClass(JsonResponse::class, "application/json");
$response = ResponseFactory::create($request);
From there, your application can continue working with the returned response instance as normal.
When this is useful
ResponseFactory is most helpful when:
- the same route can return more than one representation
- you want one response class per media type
- your application needs explicit content negotiation rather than ad hoc
ifstatements everywhere
If your project only ever returns one response type, using new Response() directly is often simpler.
All standard HTTP status exceptions are covered in this package as helper classes.