i was playing around with spatie dto library and i found myself with a problem.
how do i cast an array to a subobject?
use Spatie\DataTransferObject\DataTransferObject;
class OtherDTOCollection extends DataTransferObject {
public OtherDto $collection;
}
class OtherDTO extends DataTransferObject {
public int $id;
public string $test;
}
class MyDTO extends DataTransferObject {
public OtherDTO $collection;
}
class MyDTO2 extends DataTransferObject {
public OtherDTOCollection $collection;
}
// WORKS
$MyDTO = new MyDTO(
collection: [
[
'id' => 1,
'test' => 'test'
],
[
'id' => 1,
'test' => 'test'
]
]
);
// DOESN'T WORK
$MyDTO2 = new MyDTO2(
collection: [
[
'id' => 1,
'test' => 'test'
],
[
'id' => 1,
'test' => 'test'
]
]
);
here's the relevant code, how can i make it work so that i have an array of objects?
thanks
CodePudding user response:
You need to use the CastWith class form Spatie Attributes. .
use Spatie\DataTransferObject\Casters\ArrayCaster; use Spatie\DataTransferObject\Attributes\CastWith;
CodePudding user response:
This example will give you array of dto objects. /** @var \DTO\PrefixListItem[] */
comment has key role, type here full namespace, not on the top with use
namespace \DTO;
use Spatie\DataTransferObject\DataTransferObject;
class PrefixListResult extends DataTransferObject
{
/** @var \DTO\PrefixListItem[] */
public ?array $list = [];
public ?string $server_time = null;
public ?int $code = null;
public ?string $message = null;
public ?array $details = [];
}
namespace \DTO;
use Spatie\DataTransferObject\DataTransferObject;
class PrefixListItem extends DataTransferObject
{
public string $imsi_prefix;
public string $operator;
public int $min_sim_active_days;
public int $max_sim_active_days;
public bool $call_forwarding;
}