This example uses Dependency Injection and the target controller has constructor parameters in it.


controllers.yml


services:
application_api.controller.abstract:
class: Application\ApiBundle\Controller\AbstractController
abstract: true
arguments:
- @serializer

application_api.controller.receiver:
class: Application\ApiBundle\Controller\ReceiverController
parent: application_api.controller.abstract
arguments:
- @application_api.service.api

application_api.controller.sender:
class: Application\ApiBundle\Controller\SenderController
parent: application_api.controller.abstract
arguments:
- @http_kernel

ReceiverController


This controller also makes a call to another service by passing all the URI query parameters, request body content, http method and original request uri so you better print them out to see what exactly is being received.


/**
* @Route("/receiver", service="application_api.controller.receiver")
*/
class ReceiverController extends AbstractController
{
private $apiService;

public function __construct(
SerializerInterface $serializer,
ApiServiceInterface $apiService
) {
parent::__construct($serializer);

$this->apiService = $apiService;
}

/**
* @param Request $request
*
* @Secure(roles="ROLE_ADMIN")
*
* @Route("/give-it-to-me/{id}", requirements={"id"="([0-9]){8}"})
*
* @return Response
*/
public function givItToMeAction(Request $request)
{
$result = $this->apiService->call(
$request->getPathInfo(),
$request->getMethod(),
$request->query->all(),
$request->getContent()
);

return new Response($result);
}
}

SenderController


If the controller wasn't declared as a service, we could just use '_controller' => 'ApplicationApiBundle:Receiver:givItToMe' below.


/**
* @Route("/sender", service="application_api.controller.sender")
*/
class ReceiverController extends AbstractController
{
private $httpKernel;

public function __construct(
SerializerInterface $serializer,
HttpKernelInterface $httpKernel
) {
parent::__construct($serializer);

$this->httpKernel = $httpKernel;
}

/**
* @param Request $request
*
* @Method({"PATCH"})
* @Secure(roles="ROLE_ADMIN")
* @Route("/take-it/{id}", requirements={"id"="([0-9]){8}"})
*
* @return Response
*/
public function takeItAction(Request $request)
{
$attributes = [
'_controller' => 'application_api.controller.receiver:givItToMeAction',
'request' => $request
];
$subRequest = $request->duplicate([], null, $attributes);

/** @var Response $response */
$response = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);

return $response;
}
}

Example request


PATCH /api/sender/take-it/123
{
"key": "value"
}