PHP code example of lumenated / fractal-views

1. Go to this page and download the library: Download lumenated/fractal-views 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/ */

    

lumenated / fractal-views example snippets


class BookView extends Lumenated\FractalViews\View 
{
  // The fractal transformer that has to be used for this view
  protected $transformerClass = BookTransformer::class;
}


namespace Acme\Transformer;

use Acme\Model\Book;
use League\Fractal;

class BookTransformer extends Fractal\TransformerAbstract
{
	public function transform(Book $book)
	{
	    return [
	        'id'      => (int) $book->id,
	        'title'   => $book->title,
	        'year'    => (int) $book->yr,
            'links'   => [
                [
                    'rel' => 'self',
                    'uri' => '/books/'.$book->id,
                ]
            ],
	    ];
	}
}

namespace \App\Http\Controllers;

class BookController extends Controller 
{
  private $view;
  
  public function __construct(BookView $view) 
  {
    $this->view = $view;
    
  }
  
  public function get($id) 
  {
    $book = Book::findOrFail($id);
    
    return response()->json($this->view->render($book));
  }
  
  public function getAll() 
  {
    $books = Book::all();
    
    return response()->json($this->view->render($books));
  }
}