PHP code example of davidianbonner / presenter

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/ */

    

davidianbonner / presenter example snippets


DavidIanBonner\Presenter\PresenterServiceProvider::class

'Presenter' => DavidIanBonner\Presenter\Facades\Presenter::class,

// Transform an object
Presenter::transform(Book::find(1), BookTransformer::class);

// or with pre-set transformers
Presenter::transform(Book::find(1));

'transformers' => [
    App\Models\Book::class => App\Transformers\BookTransformer::class,
    App\OtherObject\Foo::class => App\Transformers\FooTransformer::class,
],



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());

php artisan vendor:publish --provider="DavidIanBonner\Presenter\PresenterServiceProvider"