PHP code example of ellipsesynergie / api-response
1. Go to this page and download the library: Download ellipsesynergie/api-response library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// Instantiate the fractal manager
$manager = new \League\Fractal\Manager;
// Set the request scope if you need embed data
$manager->parseIncludes(explode(',', $_GET['
use EllipseSynergie\ApiResponse\Contracts\Response;
class BookController extends Controller {
/**
* @param Response $response
*/
public function __construct(Response $response)
{
$this->response = $response;
}
/**
* Example returning collection
*/
public function index()
{
//Get all books
$books = Book::all();
// Return a collection of $books
return $this->response->withCollection($books, new BookTransformer);
}
/**
* Example returning collection with custom key
*/
public function index()
{
//Get all books
$books = Book::all();
//Custom key
$customKey = 'books';
// Return a collection of books
return $this->response->withCollection($books, new BookTransformer, $customKey);
}
/**
* Example returning collection with paginator
*/
public function index()
{
//Get all books
$books = Book::paginate(15);
// Return a collection of $books with pagination
return $this->response->withPaginator(
$books,
new BookTransformer
);
}
/**
* Example returning collection with paginator with custom key and meta
*/
public function index()
{
//Get all books
$books = Book::paginate(15);
//Custom key
$customKey = 'books';
//Custom meta
$meta = [
'category' => 'fantasy'
];
// Return a collection of $books with pagination
return $this->response->withPaginator(
$books,
new BookTransformer,
$customKey,
$meta
);
}
/**
* Example returning item
*/
public function show($id)
{
//Get the book
$book = Book::find($id);
// Return a single book
return $this->response->withItem($book, new BookTransformer);
}
/**
* Example returning item with a custom key and meta
*/
public function showWithCustomKeyAndMeta($id)
{
//Get the book
$book = Book::find($id);
//Custom key
$customKey = 'book';
//Custom meta
$meta = [
'readers' => $book->readers
];
// Return a single book
return $this->response->withItem($book, new BookTransformer, $customKey, $meta);
}
/**
* Example resource not found
*/
public function delete($id)
{
//Try to get the book
$book = Book::find($id);
//Book not found sorry !
if(!$book){
return $this->response->errorNotFound('Book Not Found');
}
}
/**
* Example method not implemented
*/
public function whatAreYouTryingToDo()
{
return $this->response->errorMethodNotAllowed("Please don't try this again !");
}
}