1. Go to this page and download the library: Download spatie/value-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/ */
spatie / value-object example snippets
use Spatie\DataTransferObject\Attributes\MapFrom;
use Spatie\DataTransferObject\DataTransferObject;
class MyDTO extends DataTransferObject
{
public OtherDTO $otherDTO;
public OtherDTOCollection $collection;
#[CastWith(ComplexObjectCaster::class)]
public ComplexObject $complexObject;
public ComplexObjectWithCast $complexObjectWithCast;
#[NumberBetween(1, 100)]
public int $a;
#[MapFrom('address.city')]
public string $city;
}
$dto = new MyDTO(
collection: [ // This will become an object of class OtherDTOCollection
['id' => 1],
['id' => 2], // Each item will be an instance of OtherDTO
['id' => 3],
],
otherDTO: ['id' => 5], // This data will be cast to OtherDTO
);
class ComplexObject
{
public string $name;
}
use Spatie\DataTransferObject\Caster;
class ComplexObjectCaster implements Caster
{
/**
* @param array|mixed $value
*
* @return mixed
*/
public function cast(mixed $value): ComplexObject
{
return new ComplexObject(
name: $value['name']
);
}
}
class MyDTO extends DataTransferObject
{
public ComplexObjectWithCast $complexObjectWithCast;
}
#[CastWith(ComplexObjectWithCastCaster::class)]
class ComplexObjectWithCast
{
public string $name;
}
#[
DefaultCast(DateTimeImmutable::class, DateTimeImmutableCaster::class),
DefaultCast(MyEnum::class, EnumCaster::class),
]
abstract class BaseDataTransferObject extends DataTransferObject
{
public MyEnum $status; // EnumCaster will be used
public DateTimeImmutable $date; // DateTimeImmutableCaster will be used
}
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(ArrayCaster::class, itemType: Foo::class)]
public array $collectionWithNamedArguments;
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(ArrayCaster::class, Foo::class)]
public array $collectionWithoutNamedArguments;
class MyDTO extends DataTransferObject
{
#[NumberBetween(1, 100)]
public int $a;
}
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
class NumberBetween implements Validator
{
public function __construct(
private int $min,
private int $max
) {
}
public function validate(mixed $value): ValidationResult
{
if ($value < $this->min) {
return ValidationResult::invalid("Value should be greater than or equal to {$this->min}");
}
if ($value > $this->max) {
return ValidationResult::invalid("Value should be less than or equal to {$this->max}");
}
return ValidationResult::valid();
}
}
class PostDTO extends DataTransferObject
{
#[MapFrom('postTitle')]
public string $title;
#[MapFrom('user.name')]
public string $author;
}
$dto = new PostDTO([
'postTitle' => 'Hello world',
'user' => [
'name' => 'John Doe'
]
]);
class UserDTO extends DataTransferObject
{
#[MapFrom(0)]
public string $firstName;
#[MapFrom(1)]
public string $lastName;
}
$dto = new UserDTO(['John', 'Doe']);
class UserDTO extends DataTransferObject
{
#[MapFrom(0)]
#[MapTo('first_name')]
public string $firstName;
#[MapFrom(1)]
#[MapTo('last_name')]
public string $lastName;
}
$dto = new UserDTO(['John', 'Doe']);
$dto->toArray() // ['first_name' => 'John', 'last_name'=> 'Doe'];
$dto->only('first_name')->toArray() // ['first_name' => 'John'];
class NonStrictDto extends DataTransferObject
{
public string $name;
}
// This works
new NonStrictDto(
name: 'name',
unknown: 'unknown'
);
use \Spatie\DataTransferObject\Attributes\Strict;
#[Strict]
class StrictDto extends DataTransferObject
{
public string $name;
}
// This throws a \Spatie\DataTransferObject\Exceptions\UnknownProperties exception
new StrictDto(
name: 'name',
unknown: 'unknown'
);
class Bar extends DataTransferObject
{
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(FooArrayCaster::class)]
public array $collectionOfFoo;
}
class Foo extends DataTransferObject
{
public string $name;
}
class FooArrayCaster implements Caster
{
public function cast(mixed $value): array
{
if (! is_array($value)) {
throw new Exception("Can only cast arrays to Foo");
}
return array_map(
fn (array $data) => new Foo(...$data),
$value
);
}
}
class Bar extends DataTransferObject
{
#[CastWith(FooCollectionCaster::class)]
public CollectionOfFoo $collectionOfFoo;
}
class Foo extends DataTransferObject
{
public string $name;
}
use Illuminate\Support\Collection;
class CollectionOfFoo extends Collection
{
// Add the correct return type here for static analyzers to know which type of array this is
public function offsetGet($key): Foo
{
return parent::offsetGet($key);
}
}
class FooCollectionCaster implements Caster
{
public function cast(mixed $value): CollectionOfFoo
{
return new CollectionOfFoo(array_map(
fn (array $data) => new Foo(...$data),
$value
));
}
}
class Bar extends DataTransferObject
{
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(ArrayCaster::class, itemType: Foo::class)]
public array $collectionOfFoo;
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.