3

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.

user2690527
  • 1,729
  • 1
  • 22
  • 38
  • Your question is a bit broad. There are however several resources and tutorials online on how to get started, so I'm just gonna link one: https://techpunch.co.uk/development/custom-annotations-in-symfony2-using-doctrine2s-annotation-classes. – Gerry Aug 12 '16 at 11:43
  • You should use the same logic as [FrameworkExtraBundle](https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/DependencyInjection/SensioFrameworkExtraExtension.php) (read the annotations in DependenciesInjection, convert them in event_listeners ... – Alsatian Aug 12 '16 at 14:39
  • to get it clear: getHtml and getJson will respond with the same resource, you want to control the output format of that resource only? – Jojo Aug 18 '16 at 13:26
  • @Jojo: Yes, that what I want. Nonetheless, the answer should be the same even if I wanted to return something totally different. However, the latter would break HTTP semantics, because the URI should uniquely identify the resource and so I do not want this. – user2690527 Aug 19 '16 at 14:36

0 Answers0