PHP code example of nimbly / remodel

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

    

nimbly / remodel example snippets


use Nimbly\Remodel\Transformer;

class UserTransform extends Transformer
{
    public function transform(User $user): array
    {
        return [
            "id" => (int) $user->id,
            "name" => $user->name,
            "email" => $user->email,
            "created_at" => \date("c", $user->created_at)
        ];
    }
}

// Grab the user from the database
$user = App\Models\User::find($id);

// Create a new Item subject using the UserTransformer
$subject = new Nimbly\Remodel\Subjects\Item($user, new UserTransformer);

class BookTransformer extends Transformer
{
    protected $defaultIncludes = ["author", "reviews"];

    public function transform(Book $book): array
    {
        return [
            "id" => (int) $book->id,
            "title" => $book->title,
            "genre" => $book->genre,
            "isbn" => $book->isbn,
            "published_at" => date("c", $book->published_at)
        ];
    }

    /**
     *
     * Remodel will call this method automatically for you since it's in the list of
     * $defaultIncludes above.
     *
     */
    public function authorInclude(Book $book): Subject
    {
        return new Item($book->author, new AuthorTransformer);
    }

    /**
     *
     * Return an array of reviews.
     *
     */
    public function reviewsInclude(Book $book): Subject
    {
        return new Collection($book->reviews, new ReviewTransformer);
    }
}

class AuthorTransformer extends Transformer
{
    public function transform(Author $author)
    {
        return [
            "id" => (int) $author->id,
            "name" => $author->name
        ];
    }
}

protected $defaultIncludes = ["author.address"];

protected $defaultIncludes = ["comments.user.profile"];

$collection = new Nimbly\Remodel\Subjects\Collection($books, new BookTransformer);

$transformer = new BookTransformer;
$transformer->setIncludes(["author", "publisher"]);

$transformer = new BookTransformer;
$transformer->setDefaultIncludes(["comments"]);