1. Go to this page and download the library: Download davidianbonner/presenter 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/ */
// Transform an object
Presenter::transform(Book::find(1), BookTransformer::class);
// or with pre-set transformers
Presenter::transform(Book::find(1));
namespace App\Transformers\BookTransformer;
use DavidIanBonner\Presenter\Transformer;
use DavidIanBonner\Presenter\Presentable;
class BookTransformer extends Transformer
{
// Optional
protected function bootTransformer(Presentable $object) { }
public function foo()
{
// Given $this->object->foo = 'bar'
// Calling $bookTransformer->foo will return "bar_mutated"
return $this->object->foo.'_mutated';
}
// Extend toArray if
use Illuminate\Support\Facades\Response;
...
public function index()
{
// Using the settings above, book will be available in the view
// as an instance of App\Transformers\BookTransformer
$data = ['book' => Book::find(1)];
return Response::present('view-name', $data, $statusCode, $headers);
}
public function index()
{
return present('view-name', ['book' => Book::find(1)], $statusCode, $headers);
}
use Illuminate\Http\JsonResponse;
...
public function index()
{
// Using the settings above, book will be transformed and
// built from App\Transformers\BookTransformer
$data = ['book' => Book::find(1)];
return JsonResponse::present($data, $statusCode, $headers, $options);
}
// Get a collection of BookTransformer objects
Collection::present(Book::get());