PHP code example of imbue / data-transfer-object

1. Go to this page and download the library: Download imbue/data-transfer-object 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/ */

    

imbue / data-transfer-object example snippets


class BookData extends DataTransferObject
{
    protected $title;
    protected $author;

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @return AuthorData
     */
    public function getAuthor(): AuthorData
    {
        return $this->author;
    }
}

class BookData extends DataTransferObject
{
    protected $title;
    protected $author;

    /**
     * @param nullable|string $title
     */
    public function setTitle(?string $title)
    {
        return $this->title;
    }

    /**
     * @param AuthorData $author
     */
    public function setAuthor(AuthorData $author)
    {
        return $this->author;
    }
}

return $dataObject->toArray();

return $dataObject->toJson();

$collection = new BooksCollection([
    $bookOne,
    $bookTwo,
    $bookThree
]);

$collection->toArray();

class BooksCollection extends DataTransferObjectCollection
{
    public function current(): BookData
    {
        return parent::current();
    }
}

foreach ($booksCollection as $bookData) {
    $bookData-> // type hinting 
}

$dataObject
    ->only('title')
    ->toArray();

$dataObject
    ->except('title')
    ->toArray();

$book = new BookData();
$book->setTitle('Harry Potter: The Goblet of Fire');

$author = new Author();
// ....

$book->setAuthor($author);