My controllers return different content types with respect to theHTTP
Accept
header sent by the client. At the moment on a high level my controllers follow this pattern:
/**
* @Route("/SomePath")
* @Method({"GET"})
* @param Request $request The HTTP request
* @return Symfony\Component\HttpFoundation\Response The HTTP response
*/
public function getSomething( Request $request ) {
$acceptedTypes = $request->getAcceptableContentTypes();
if( in_array('text/html', $acceptedTypes ) )
return $this->getSomethingHTML( $request );
if( in_array('application/json', $acceptedTypes ) )
return $this->getSomethingJSON( $request );
throw new NotAcceptableHttpException();
}
public function getSomethingHTML( Request $request ) {
// ...
}
public function getSomethingHTML( Request $request ) {
// ...
}
I want to achieve something like this to avoid this unnecessary and repeating first method:
/**
* @Route("/SomePath")
* @Method({"GET"})
* @Accepts("text/html")
* @param Request $request The HTTP request
* @return Symfony\Component\HttpFoundation\Response The HTTP response
*/
public function getSomethingHTML( Request $request ) {
// ...
}
/**
* @Route("/SomePath")
* @Method({"GET"})
* @Accepts("application/json")
* @param Request $request The HTTP request
* @return Symfony\Component\HttpFoundation\JsonResponse The HTTP response
*/
public function getSomethingJSON( Request $request ) {
// ...
}
Here. @Accepts
is a new, custom annotation that only matches if the given string is found in the array of acceptable content types of the request. How do I implement my own @Accepts
annotation and how do I make Symfony aware of it?
N.b.: I know I could achieve a 90% solution if I used the condition
parameter of @Route
. However, this would still entail a lot of repeating code.