1. Go to this page and download the library: Download knobik/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/ */
knobik / data-transfer-object example snippets
public function handleRequest(array $dataFromRequest)
{
$dataFromRequest[/* what to do now?? */];
}
class PostData extends DataTransferObject
{
// …
public static function fromRequest(Request $request): self
{
return new self([
'title' => $request->get('title'),
'body' => $request->get('body'),
'author' => Author::find($request->get('author_id')),
]);
}
}
class PostData extends DataTransferObject
{
/**
* Built in types:
*
* @var string
*/
public $property;
/**
* Classes with their FQCN:
*
* @var \App\Models\Author
*/
public $property;
/**
* Lists of types:
*
* @var \App\Models\Author[]
*/
public $property;
/**
* Union types:
*
* @var string|int
*/
public $property;
/**
* Nullable types:
*
* @var string|null
*/
public $property;
/**
* Mixed types:
*
* @var mixed|null
*/
public $property;
/**
* No type, which allows everything
*/
public $property;
}
use \Spatie\DataTransferObject\DataTransferObjectCollection;
class PostCollection extends DataTransferObjectCollection
{
public function current(): PostData
{
return parent::current();
}
}
foreach ($postCollection as $postData) {
$postData-> // … your IDE will provide autocompletion.
}
$postCollection[0]-> // … and also here.
class PostCollection extends DataTransferObjectCollection
{
public static function create(array $data): PostCollection
{
$collection = [];
foreach ($data as $item)
{
$collection[] = PostData::create($item);
}
return new self($collection);
}
}
class PostData extends DataTransferObject
{
/** @var \AuthorData */
public $author;
}