1. Go to this page and download the library: Download dldash/data-transfer-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/ */
dldash / data-transfer-object example snippets
use Dldash\DataTransferObject\Models\DataTransferObject;
class UserDto extends DataTransferObject
{
public function __construct(
public int $userId,
public string|null $username
) {}
}
use Dldash\DataTransferObject\Contracts\ValueObjectContract;
class EmailAddress implements ValueObjectContract, JsonSerializable
{
public function __construct(private string $value)
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Email address [${value}] is not valid.");
}
$this->value = strtolower($value);
}
public function value(): string
{
return $this->value;
}
public function jsonSerialize(): string
{
return $this->value;
}
}
use Dldash\DataTransferObject\Models\DataTransferObject;
class OrderDto extends DataTransferObject
{
public function __construct(
public int $orderId,
public EmailAddress $emailAddress
) {}
}
use Dldash\DataTransferObject\Models\DataTransferObject;
class OrderDto extends DataTransferObject
{
public function __construct(
public int $orderId,
public UserDto $user
) {}
}
use Dldash\DataTransferObject\Objects\DataTransferObjectCollection;
/** @method ArrayIterator|UserDto[] getIterator() */
class UserDtoCollection extends DataTransferObjectCollection
{
protected function create(mixed $item): object
{
return UserDto::create($item);
}
}
use Dldash\DataTransferObject\Models\DataTransferObject;
class OrderDto extends DataTransferObject
{
public function __construct(
public int $orderId,
public UserDtoCollection $users
) {}
}
use Dldash\DataTransferObject\Objects\Undefined;
use Dldash\DataTransferObject\Models\DataTransferObject;
class OrderDto extends DataTransferObject
{
public function __construct(
public int $orderId,
public string|null|Undefined $name
) {}
}
use Dldash\DataTransferObject\Objects\Undefined;
$request = [
'orderId' => 100
];
$dto = OrderDto::create($request);
if (Undefined::isPresent($dto->name)) {
// Update this field
}
use Dldash\DataTransferObject\Attributes\SerializedName;
use Dldash\DataTransferObject\Models\DataTransferObject;
class OrderDto extends DataTransferObject
{
public function __construct(
#[SerializedName('order_id')]
public int $id,
#[SerializedName('order_name')]
public string $name
) {}
}