Skip to content

Instantly share code, notes, and snippets.

@marinsagovac
Created February 26, 2018 16:42
Show Gist options
  • Save marinsagovac/701c0272fb7a8a8d2ae65261ca2cba34 to your computer and use it in GitHub Desktop.
Save marinsagovac/701c0272fb7a8a8d2ae65261ca2cba34 to your computer and use it in GitHub Desktop.
# Find some custom route: bin/console debug:router
# example: api_countries_get_item
# Create a Controller/CountriesSpecial.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Countries;
use Symfony\Component\Routing\Annotation\Route;
class CountriesSpecial
{
private $myService;
/*
public function __construct(MyService $myService)
{
$this->myService = $myService;
}*/
/**
* @Route(
* name="api_countries_get_item",
* path="/countries/{id}",
* methods={"GET"},
* defaults={"_api_resource_class"=Countries::class, "_api_item_operation_name"="countries"}
* )
*/
public function __invoke(Countries $data): object // API Platform retrieves the PHP entity using the data provider then (for POST and
// PUT method) deserializes user data in it. Then passes it to the action. Here $data
// is an instance of Book having the given ID. By convention, the action's parameter
// must be called $data.
{
//die('x');
//$this->myService->doSomething($data);
return $data; // API Platform will automatically validate, persist (if you use Doctrine) and serialize an entity
// for you. If you prefer to do it yourself, return an instance of Symfony\Component\HttpFoundation\Response
}
public function special(Countries $data)
{
// Handle custom action
// Here you go, i've added custom arrays inside
return array($data, array('key' => 'custom'));
}
}
# Add routes into routing.yml
api_countries_get_item:
path: '/countries/{id}'
methods: ['GET']
defaults:
_controller: '\AppBundle\Controller\CountriesSpecial::special'
_api_resource_class: 'AppBundle\Entity\Countries'
_api_item_operation_name: 'special'
On Entity Countries.php put:
/**
* Country
*
* @ApiResource{
* "get",
* "special"={"route_name"="countries_special"},
* }
* @ORM\Entity
* @ORM\Table(name="country")
*/
class Countries
{
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment