Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active June 16, 2022 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/6cb5242574391ead1ed8257a5cfd9ef2 to your computer and use it in GitHub Desktop.
Save mtvbrianking/6cb5242574391ead1ed8257a5cfd9ef2 to your computer and use it in GitHub Desktop.
Spatie Data Transfer Object
<?php
// ..............................................
// V2
// ..............................................
use Spatie\DataTransferObject\DataTransferObject;
class Item extends DataTransferObject
{
/** @var int|string $id */
public $id;
public string $name;
}
class ListItems extends DataTransferObject
{
/** @var Item[] */
public array $items;
}
// ..............................................
// V3 using array casters
// ..............................................
use Spatie\DataTransferObject\Caster;
class ItemArrayCaster implements Caster
{
public function cast(mixed $values): array
{
if (! \is_array($values)) {
throw new \Exception('Can only cast arrays to Item');
}
return array_map(function ($value) {
return new Item($value);
}, $values);
}
}
use Spatie\DataTransferObject\Attributes\CastWith;
class ListItems extends DataTransferObject
{
#[CastWith(ItemArrayCaster::class)]
public array $items;
}
// ..............................................
$item = new Item(['id' => 1, 'label' => 'jdoe']);
$items = [
['id' => 1, 'label' => 'jdoe'],
['id' => '2', 'label' => 'bmatovu'],
];
$list1 = new ListItems(items: $items);
$_list1 = $list1->toArray();
$list2 = new ListItems($_list1);
$list2->items[1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment