PHP code example of soyhuce / data-transfer-object-casts
1. Go to this page and download the library: Download soyhuce/data-transfer-object-casts 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/ */
soyhuce / data-transfer-object-casts example snippets
use Soyhuce\DataTransferObjectCasts\BooleanCaster;
use Spatie\DataTransferObject\Attributes\DefaultCast;
use Spatie\DataTransferObject\DataTransferObject;
#[DefaultCast('bool', BooleanCaster::class)]
class MyDTO extends DataTransferObject
{
public bool $bool;
}
$dto = new MyDTO(
bool: 'true',
);
$dto->bool; // true
use Carbon\CarbonImmutable;
use Soyhuce\DataTransferObjectCasts\CarbonImmutableCaster;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\DefaultCast;
use Spatie\DataTransferObject\DataTransferObject;
#[DefaultCast(CarbonImmutable::class, CarbonImmutableCaster::class)]
class MyDTO extends DataTransferObject
{
public CarbonImmutable $dateTime;
#[CastWith(CarbonImmutableCaster::class, '!Y-m-d')]
public CarbonImmutable $date;
}
$dto = new MyDTO(
dateTime: '2022-08-11 14:44:45',
date: '2022-08-01',
);
$dto->dateTime; // CarbonImmutable instance
$dto->date; // CarbonImmutable instance
use Soyhuce\DataTransferObjectCasts\StringEnumCaster;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\DataTransferObject;
#[CastWith(StringEnumCaster::class)]
enum StringEnum: string
{
case ok = 'ok';
case nok = 'nok';
}
class MyDTO extends DataTransferObject
{
public StringEnum $stringEnum;
}
$dto = new MyDTO(
stringEnum: 'ok',
);
$dto->stringEnum; // StringEnum::ok
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.