A silex service provider that provides tools for doing HTTP content negotiation.
MIT License
The silex-conneg-provider is a silex service provider that provides tools for doing
HTTP Content Negotiation in your application. It allows you
to declare which request and response formats your application can handle. If the client requests a response in a
format your application does not support, they will get a 406 Not Acceptable
response. If the client sends a request
body in a format your application does not support, they will get a 415 Unsupported Media Type
response. There is also
a service to make it easy to automatically serialize responses and deserialize requests using
JMS Serialzier or
Symfony Serializer.
Install the silex-conneg-provider using composer. This project uses sematic versioning.
{
"require": {
"jdesrosiers/silex-conneg-provider": "~1.0"
}
}
Content Negotiation
array("html")
array("form")
Serialization
html
Respose::create
, but takes an object instead of a string and serializes it$app->register(new JDesrosiers\Silex\Provider\ContentNegotiationServiceProvider(), array(
"conneg.responseFormats" => array("json", "xml"),
"conneg.requestFormats" => array("json", "xml"),
"conneg.defaultFormat" => "json",
));
The service provider adds middleware that does all of the content negotiation header validation automatically and
responds appropriately when the request can not be handled. You can get the response format determined by the
middleware using the Request::getRequestFormat
method.
$request->getRequestFormat($defaultFormat);
The conneg
service provides some helper functions for automatically serailizing responses and deserializing requests.
This functionality is available if you have an instance of either the JMS Serialzier
or the Symfony Serializer accessible at
$app["serializer"]
. You can get the JMS Serializer from the
jdesrosiers/silex-jms-serializer-provider or the Symfony
Serializer from the silex built-in SerializerServiceProvider
.
$app->post("/foo", function (Request $request) use ($app) {
// deserializeRequest takes the class name of a JMS Serializer annotated class and will deserialize
// the request entity and give you back an instance of that class.
$requestData = $app["conneg"]->deserializeRequest("FooRequest");
$response = Foo::create($requestData);
// createResponse works just like Respose::create, but takes a JMS Serializer annotated object
// instead of a string and serializes it to the format the user requested.
return $app["conneg"]->createResponse($response, 201, array(
"Location" => "/foo/1234",
));
});