Last active
June 16, 2022 16:52
-
-
Save mtvbrianking/6cb5242574391ead1ed8257a5cfd9ef2 to your computer and use it in GitHub Desktop.
Spatie Data Transfer Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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