perfilov / php-dto-packer
Convert array, json, objects into a strongly-typed values (and back) for transferring throw services
Installs: 1 839
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 1
Requires
- php: >=8.1
This package is auto-updated.
Last update: 2025-04-12 16:06:05 UTC
README
DtoPacker is a small PHP library to pack data into a strongly-typed value object structure. Use it when you want to transfer objects between services and send to front.
Write to me if you need additional features
PerfilovStanislav
Install
composer require perfilov/php-dto-packer
Quick Example
Prepare structure
use DtoPacker\AbstractDto; class Family extends AbstractDto { public string $surname; protected array|Person $persons; public bool $hasCar; } class Person extends AbstractDto { public string $name; public \DateTime $birthday; protected PersonTypeEnum $type; protected array|string $friends; } enum PersonTypeEnum { case HUSBAND; case WIFE; case CHILD; }
Create DTO from array
$family = new Family([ 'surname' => 'Perfilov', 'persons' => [ [ // from array 'name' => 'Stanislav', 'birthday' => '1987-12-13T12:05:55+03:00', 'type' => 'HUSBAND', 'friends' => ['Elon Musk', 'Guy Ritchie'], ], new Person([ // or object 'name' => 'Natali', 'type' => PersonTypeEnum::WIFE, 'birthday' => \DateTime::createFromFormat('d.m.Y', '28.11.1994'), ]),[ 'name' => 'Leo', 'type' => 'CHILD', ], ], ]); // or set it manually $family->persons[2]->friends = ['Jason Statham', 'John Depp'];
Convert DTO to array
$arr = $family->toArray(); Output: [ "surname" => "Perfilov" "persons" => [ [ "name" => "Stanislav" "birthday" => "1987-12-13T12:05:55+03:00" "type" => "HUSBAND" "friends" => ["Elon Musk", "Guy Ritchie"] ], [ "name" => "Natali" "birthday" => "1994-11-28T21:02:13+00:00" "type" => "WIFE" ], [ "name" => "Leo" "type" => "CHILD" "friends" => ["Jason Statham", "John Depp"] ] ] ]
Convert DTO to string/json
$json = (string)$family; Output: {"surname":"Perfilov","persons":[{"name":"Stanislav","birthday":"1987-12-13T12:05:55+03:00","type":"HUSBAND","friends":["Elon Musk","Guy Ritchie"]},{"name":"Natali","birthday":"1994-11-28T21:11:57+00:00","type":"WIFE"},{"name":"Leo","type":"CHILD","friends":["Jason Statham","John Depp"]}]}
Create DTO from json
$family = new Family($json);