1. Go to this page and download the library: Download phpexperts/simple-dto 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/ */
phpexperts / simple-dto example snippets
use Carbon\Carbon;
use PHPExperts\SimpleDTO\SimpleDTO;
/**
* @property-read string $name
* @property-read Carbon $date
*/
class BirthdayDTO extends SimpleDTO
{
/** @var string */
protected $name;
/** @var Carbon */
protected $date;
}
$birthdayDTO = new BirthdayDTO([
'name' => 'Donald J. Trump',
'date' => '1946-06-14',
]);
// Access as a property:
echo $birthday->name; // Donald J. Trump
// Properties with the data type of "Carbon" or "Carbon\Carbon"
// are automagically converted to Carbon objects.
echo $birthday->date->format('F jS, Y'); // June 14th, 1946
// Easily output as an array:
$birthday->toArray();
// Copy from one to another:
$newDTO = new BirthdayDTO($birthdayDTO->toArray());
// Copy from one to another, with new properties:
$newDTO = new BirthdayDTO($birthdayDTO->toArray() + [
'date' => '2020-11-03',
]);
// Easily output as JSON:
echo json_encode($birthdayDTO);
/* Output:
{
"name": "Donald J. Trump",
"date": "1946-06-14T00:00:00.000000Z"
}
*/
use PHPExperts\DataTypeValidator\DataTypeValidator;
use PHPExperts\DataTypeValidator\IsAFuzzyDataType;
/**
* @property int $daysAlive
* @property float $age
* @property bool $isHappy
*/
class MyFuzzyDTO extends SimpleDTO
{
public function __construct(array $input)
{
parent::__construct($input, new DataTypeValidator(new IsAFuzzyDataType());
}
}
$person = new MyFuzzyDTO([
'daysAlive' => '5000',
'age' => '13.689',
'isHappy' => 1,
]);
echo json_encode($person, JSON_PRETTY_PRINT);
/*
{
"daysAlive": "5000",
"age": "13.689",
"isHappy": 1
}
*/
/**
* @property string $name
*/
class CityDTO extends SimpleDTO
{
use WriteOnce;
protected int $population;
}
$cityDTO = new CityDTO(['name' => 'Dubai']);
dd($cityDTO);
$testDTO = new class(['name' => 'Sofia', 'birthYear' => 2010]) extends SimpleDTO {
#[IgnoreAsDTO]
protected int $age;
protected string $name;
protected int $birthYear;
public function calcAge(): int
{
$this->age = date('Y') - $this->birthYear;
return $this->age;
}
};