3

HTTP Accept私のコントローラーは、クライアントから送信されたヘッダーに関してさまざまなコンテンツ タイプを返します。現時点では、私のコントローラーは次のパターンに従います。

/**
 * @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 ) {
  // ...
}

この不要で繰り返しの最初の方法を避けるために、このようなことを達成したいと思います。

/**
 * @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 ) {
  // ...
}

ここ。@Accepts指定された文字列がリクエストの許容可能なコンテンツ タイプの配列で見つかった場合にのみ一致する、新しいカスタム アノテーションです。独自のアノテーションを実装するにはどうすればよい@Acceptsですか? また、Symfony にそれを認識させるにはどうすればよいですか?

condition注: のパラメーターを使用した場合、90% の解を達成できることがわかっています@Route。ただし、これにはまだ多くの繰り返しコードが必要です。

4

0 に答える 0