PHP code example of rmezhuev / data-transfer-object
1. Go to this page and download the library: Download rmezhuev/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/ */
rmezhuev / data-transfer-object example snippets
use RMezhuev\DTO\DataObject;
/**
* @property string $name
* @property string $email
* @property string|int|null $age
* @property array|null $phone
* @property CustomType|null $details
*/
class PersonDto extends DataObject
{
}
$personDto = new PersonDto([
'email' =>'[email protected] ',
'name' => 'John Doe',
'age' => 35,
]);
class PersonDto extends DataObject
{
public static function fromRequest(Request $request): self
{
return new self(
$request->only([
'email',
'name',
])
);
}
public static function fromApi(array $data): self
{
return new self([
'email' => $data['primary_email'],
'name' => $data['full_name'],
]);
}
}
$personDto = new PersonDto([
'name' => 'John Doe',
'email' =>'[email protected] ',
]);
echo($personDto->name); //John Doe
echo($personDto->email); //[email protected]
echo($personDto['name']); //John Doe
echo($personDto['email']); //[email protected]
class PersonDto extends DataObject
{
protected $snakeOnSerialize = false;
}
$personDto = new PersonDto([
'name' => 'John Doe',
'email' =>'[email protected] ',
]);
$personDto->toArray();
// Result:
// [
// "name" => "John Doe"
// "email" => "[email protected] "
// "age" => null
// "phone" => null
// "details" => null
// ]
$personDto->partial()->toArray();
// Result:
// [
// "name" => "John Doe"
// "email" => "[email protected] "
// ]
class PersonDto extends DataObject
{
public static function toArray(): array
{
return [
'full_name' => $this->name,
'email' => $this->email,
'year' => date("Y") - $this->age
];
}
}