14/01/2016 - SYMFONY
Bu örnek Dependency Injection yöntemi kullanıyor ve hedef controller constructor parametreleri kullanıyor.
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
Bu controller diğer controllerdan aldığı bilgileri (URI query parameters, request body content, http method ve orjinal request uri), kendi içinde ayrıca bir API servisine request olarak iletiyor, o nedenle gelen verileri kontrol etmenizde fayda var.
/**
* @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);
}
}
Eğer controller servis olarak tanımlanmamış olsaydı, aşağıda '_controller' => 'ApplicationApiBundle:Receiver:givItToMe'
kodunu kullanabilirdiniz.
/**
* @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;
}
}
PATCH /api/sender/take-it/123
{
"key": "value"
}