-
Notifications
You must be signed in to change notification settings - Fork 0
Usage
Vitalijs Litvinovs edited this page Sep 30, 2019
·
3 revisions
All you need for your custom DTO is extending from
CodinPro\DataTransferObject\DTO class and
defining fields as protected
(phpdoc @property if you want autocomplete in your IDE). That's it!
<?php
namespace CodinPro\DataTransferObject;
/**
* @property bool|mixed $foo
* @property string|mixed $bar
* @property array|mixed $extra
*/
class ExampleDTO extends DTO
{
protected $foo = true;
protected $bar = 'string';
protected $extra = ['a' => 'b'];
}
After this "painful" setup, you can use fresh-made DTO like follows:
$dto = new ExampleDTO();
$dto->foo; // true
$dto->bar; // "string"
$dto->extra; // ["a" => "b"]
// its allowed to init from array, object or json
$dto = new ExampleDTO('{"extra":"some extra value"}');
$dto->foo; // true
$dto->bar; // "string"
$dto->extra; // "some extra value"
$dto = new ExampleDTO();
$dto->foo = 'baz'; // "baz"
$dto['bar'] = 'test'; // "test"
$dto = new ExampleDTO(['foo' => "baz"]);
$dto->foo; // "baz"
unset($dto->foo); // removes current value of "foo", getting back to default value "true"
$dto->foo; // true
$dto->bar; // "string"
$dto->extra; // ["a" => "b"]
$dto = new ExampleDTO(['extra' => ['a' => ['b' => ['c' => 'd']]]]);
$dto->foo; // "baz"
unset($dto->foo); // removes current value of "foo", getting back to default value "true"
$dto->foo; // true
$dto->bar; // "string"
$dto->extra; // ['a' => ['b' => ['c' => 'd']]]
$dto['extra']; // ['a' => ['b' => ['c' => 'd']]]
$dto->get('extra'); // ['a' => ['b' => ['c' => 'd']]]
$dto->get('extra.a'); // ['b' => ['c' => 'd']]
$dto->get('extra.a.b'); // ['c' => 'd']
$dto->get('extra.a.b.c'); // "d"
$dto = new ExampleDTO();
// when trying to convert to string, it calls inner $this->serialize();
(string)$dto; // {"foo":true,"bar":"string","extra":{"a":"b"}}
By default, it's using built-in JsonSerializer, but you can implement from DTOSerializerInterface and make your own.
$dto->setSerializer($serializer);
// or as second param in DTO constructor
$dto = new ExampleDTO([], $serializer);