### Install Atlcom DTO Source: https://github.com/atlcomgit/dto/blob/master/README.md Install the Atlcom DTO library using Composer. ```bash composer require atlcom/dto ``` -------------------------------- ### Set and Get Custom Options in DTO Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates how to set and retrieve custom options associated with a DTO instance using `setCustomOption` and `getCustomOption`. ```php class CarDto extends \Atlcom\Dto { } $carDto = CarDto::create()->setCustomOption('test', 1); /* Вывод результата */ print_r($carDto->getCustomOption('test')); ``` -------------------------------- ### DTO Exception Handling with onException Event Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates how to use the `onException` event to handle errors that occur during DTO filling or array conversion. The example shows how to catch and re-throw exceptions. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; protected function onException(\Throwable $exception): void { // Сохраняем $exception в лог throw $exception; } } $carDto = CarDto::create(); ``` -------------------------------- ### Get DTO properties with `getProperties()` Source: https://context7.com/atlcomgit/dto/llms.txt The `getProperties()` static method returns an array of public property names defined in the DTO. Variants like `getPropertiesWithFirstType()` and `getPropertiesWithAllTypes()` provide type information. ```php class CarDto extends \Atlcom\Dto { public string $markName; public ?int $year; public string|null $color; } print_r(CarDto::getProperties()); // ['markName', 'year', 'color'] print_r(CarDto::getPropertiesWithFirstType()); // ['markName' => 'string', 'year' => 'int', 'color' => 'string'] print_r(CarDto::getPropertiesWithAllTypes()); // ['markName' => ['string'], 'year' => ['int', 'null'], 'color' => ['string', 'null']] ``` -------------------------------- ### Get an empty array template with `toArrayBlank()` Source: https://context7.com/atlcomgit/dto/llms.txt The `toArrayBlank()` static method returns an array with keys corresponding to the DTO's public properties, all initialized to `null`. This provides a template for the expected structure. ```php class CarDto extends \Atlcom\Dto { public string $markName; public ?int $year; public ?string $color; } print_r(CarDto::toArrayBlank()); // ['markName' => null, 'year' => null, 'color' => null] ``` -------------------------------- ### Get DTO Hash Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Converts DTO properties to an array and returns a hash relative to the DTO. This is useful for comparing DTO states. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public Carbon $year; } $carDto = CarDto::create(year: Carbon::parse('2024-01-01 00:00:00')); /* Вывод результата */ print_r($carDto->getHash()); ``` -------------------------------- ### Create DTO with arguments Source: https://github.com/atlcomgit/dto/blob/master/README.md Use the `create` method to instantiate a DTO with named arguments or the `fill` method for an associative array. ```php $exampleDto = ExampleDto::create(a: 1, b: 2, c: null); $exampleDto = ExampleDto::fill(['a' => 1, 'b' => 2, 'c' => null]); ``` -------------------------------- ### Include protected/private properties with `withProtectedKeys()` / `withPrivateKeys()` Source: https://context7.com/atlcomgit/dto/llms.txt These methods allow the inclusion of protected and private properties in the serialized output. `withProtectedKeys(true)` includes all protected properties, while `withPrivateKeys(true)` includes all private properties. ```php class SumDto extends \Atlcom\Dto { protected int $x; protected int $y; protected int $sum = 0; protected function onAssigned(string $key): void { $this->sum = ($this->x ?? 0) + ($this->y ?? 0); } } $dto = SumDto::create(x: 10, y: 32); print_r($dto->withProtectedKeys(true)->toArray()); // ['x' => 10, 'y' => 32, 'sum' => 42] ``` -------------------------------- ### Get object state hash with `getHash()` Source: https://context7.com/atlcomgit/dto/llms.txt The `getHash()` method generates a string hash representing the current state of the DTO object. This is useful for caching and comparing DTO states. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public \Carbon\Carbon $year; } $dto = CarDto::create(year: \Carbon\Carbon::parse('2024-01-01')); echo $dto->getHash(); // CarDto:81f2a8e48ec40ca36faffa1eec01dc5c2b191b088adcccf7814214090218a308 ``` -------------------------------- ### DTO Filling with onFilling Event Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates how to use the `onFilling` event to set DTO properties before they are populated. This is useful for setting default or derived values. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; protected function onFilling(array &$array): void { $array['markName'] = 'Lexus'; $array['modelName'] = 'RX500'; } } $carDto = CarDto::create(); /* Вывод результата */ print_r($carDto->toArray()); ``` -------------------------------- ### create() - Creating DTOs Source: https://context7.com/atlcomgit/dto/llms.txt The static factory method `create()` is the primary way to instantiate DTOs. It supports creating DTOs from named arguments, associative arrays, objects, JSON strings, or other DTO instances. ```APIDOC ## create() - Creating DTOs ### Description Static factory method `create()` is the primary way to instantiate DTOs. It supports creating DTOs from named arguments, associative arrays, objects, JSON strings, or other DTO instances. ### Method `static create(mixed ...$args) ``` -------------------------------- ### Working with Date and Time Properties Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates how to convert date and time types to a single specified type using AUTO_DATETIME_CLASS. Ensure the correct class is set for AUTO_DATETIME_CLASS to control the output type. ```php class CarbonDto extends \Atlcom\Dto { public const AUTO_DATETIME_CLASS = \Carbon\Carbon::class; public \Carbon\Carbon $date1; public \DateTime $date2; public \Carbon\Carbon|\DateTime $date3; protected function casts(): array { return [ 'date1' => \Carbon\Carbon::class, 'date2' => \DateTime::class, 'date3' => 'datetime', ]; } } class DateTimeDto extends \Atlcom\Dto { public const AUTO_DATETIME_CLASS = \DateTime::class; public \Carbon\Carbon $date1; public \DateTime $date2; public \Carbon\Carbon|\DateTime $date3; protected function casts(): array { return [ 'date1' => \Carbon\Carbon::class, 'date2' => \DateTime::class, 'date3' => 'datetime', ]; } } $date1 = '2024-01-01 00:00:00'; $date2 = '2024-01-02 00:00:00'; $date3 = '2024-01-03 00:00:00'; $carbonDto = CarbonDto::create([ 'date1' => $date1, 'date2' => $date2, 'date3' => $date3, ]); $dateTimeDto = DateTimeDto::create([ 'date1' => $date1, 'date2' => $date2, 'date3' => $date3, ]); /* Вывод результата */ print_r($carbonDto->toArray()); print_r($dateTimeDto->toArray()); ``` -------------------------------- ### onCreating(array &$data) Source: https://github.com/atlcomgit/dto/blob/master/README.md Hook method called before creating and populating the DTO. ```APIDOC ## onCreating(array &$data) ### Description Hook method called before creating and populating the DTO. ### Method protected ### Parameters - **data** (array) - The data array to be used for populating the DTO. ### Response void ``` -------------------------------- ### onFilling() / onFilled() Hooks for DTO Population Source: https://context7.com/atlcomgit/dto/llms.txt Implement `onFilling()` to alter data just before it populates the DTO, and `onFilled()` to perform actions after population. These are useful for enriching data during each fill operation. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; public string $displayName; protected function onFilling(array &$array): void { // Добавляем поле до заполнения $array['markName'] = strtoupper($array['markName'] ?? ''); } protected function onFilled(array $array): void { // Вычисляем поле после заполнения $this->displayName = $this->markName . ' ' . $this->modelName; } } $dto = CarDto::create(['markName' => 'lexus', 'modelName' => 'RX500']); print_r($dto->toArray()); // ['markName' => 'LEXUS', 'modelName' => 'RX500', 'displayName' => 'LEXUS RX500'] ``` -------------------------------- ### Dynamic Properties via Options in DTO Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Shows how to enable and use dynamic properties in a DTO by setting the `AUTO_DYNAMIC_PROPERTIES_ENABLED` constant to true. This allows direct access to properties defined during creation. ```php class CarDto extends \Atlcom\Dto { public const AUTO_DYNAMIC_PROPERTIES_ENABLED = true; } $carDto = CarDto::create(test: 1); /* Вывод результата */ print_r($carDto->test); ``` -------------------------------- ### Create DTO from various sources Source: https://context7.com/atlcomgit/dto/llms.txt Use the static `create()` method to instantiate DTOs from named arguments, associative arrays, objects, JSON strings, or other DTOs. This is the primary method for creating DTO instances. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; } // Из именованных аргументов $dto = CarDto::create(markName: 'Lexus', modelName: 'RX500'); // Из ассоциативного массива $dto = CarDto::create(['markName' => 'Lexus', 'modelName' => 'RX500']); // Из объекта $dto = CarDto::create((object)['markName' => 'Lexus', 'modelName' => 'RX500']); // Из строки JSON $dto = CarDto::create('{"markName": "Lexus", "modelName": "RX500"}'); // Из другого Dto $dto2 = CarDto::create($dto); print_r($dto->toArray()); // ['markName' => 'Lexus', 'modelName' => 'RX500'] ``` -------------------------------- ### onAssigning() / onAssigned() Hooks for Property Changes Source: https://context7.com/atlcomgit/dto/llms.txt Use `onAssigning()` to intercept property assignments before they occur and `onAssigned()` to react after. `onAssigned()` is particularly useful for private/protected properties and implementing reactive logic between DTO properties. ```php class OrderDto extends \Atlcom\Dto { protected float $price = 0; protected int $quantity = 0; protected float $total = 0; protected function onAssigned(string $key): void { // Пересчитываем total при изменении price или quantity if (in_array($key, ['price', 'quantity'])) { $this->total = $this->price * $this->quantity; } } } $dto = OrderDto::create(price: 1500.0, quantity: 3); print_r($dto->withProtectedKeys(true)->toArray()); // ['price' => 1500.0, 'quantity' => 3, 'total' => 4500.0] ``` -------------------------------- ### onAssigning(string $key, mixed $value) Source: https://github.com/atlcomgit/dto/blob/master/README.md Hook method executed before changing the value of a DTO property. Requires PROTECTED or PRIVATE visibility for the property. ```APIDOC ## onAssigning(string $key, mixed $value) ### Description Hook method executed before changing the value of a DTO property. Requires PROTECTED or PRIVATE visibility for the property. ### Method protected ### Parameters - **key** (string) - The key of the property being assigned. - **value** (mixed) - The new value for the property. ### Response void ``` -------------------------------- ### DTO Creation with Lifecycle Events Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Illustrates the use of `onCreating` and `onCreated` lifecycle events during DTO instantiation. `onCreating` allows modification of input data before creation, and `onCreated` is called after the DTO is fully initialized. ```php class CarDto extends \Atlcom\Dto { public string $markName; protected function onCreating(mixed &$data): void { $data = ['markName' => 'Toyota']; } protected function onCreated(mixed $data): void { $this->markName = 'Toyota'; } } $carDto = CarDto::create(markName: 'Lexus'); /* Вывод результата */ print_r($carDto->markName); ``` -------------------------------- ### withProtectedKeys() / withPrivateKeys() Source: https://context7.com/atlcomgit/dto/llms.txt Includes protected or private properties in the serialized output. By default, only public properties are included. ```APIDOC ## withProtectedKeys() / withPrivateKeys() ### Description Includes protected or private properties in the serialized output. By default, only public properties are included. ### Method `withProtectedKeys(bool $include)` `withPrivateKeys(bool $include)` ### Parameters #### Path Parameters - **include** (bool) - Required - Set to `true` to include protected/private keys, `false` otherwise. ### Request Example ```php $dto = SumDto::create(x: 10, y: 32); print_r($dto->withProtectedKeys(true)->toArray()); ``` ### Response Example ```json { "x": 10, "y": 32, "sum": 42 } ``` ``` -------------------------------- ### Configure App Providers in Laravel Source: https://github.com/atlcomgit/dto/blob/master/docs/LARAVEL.md Include the DtoServiceProvider in your application's configuration file to ensure it's loaded. ```php return [ // ... 'providers' => [ // ... App\Providers\DtoServiceProvider::class, ], ]; ``` -------------------------------- ### Interface Implementations Source: https://github.com/atlcomgit/dto/blob/master/README.md Implementations of standard PHP interfaces to enhance DTO functionality. ```APIDOC ## ArrayAccess ### Description Enables the ArrayAccess interface for treating the DTO like an array. ## Countable ### Description Enables the Countable interface for using the `count()` method. ## IteratorAggregate ### Description Enables the IteratorAggregate interface for using the `getIterator()` method. ## JsonSerializable ### Description Enables the JsonSerializable interface for `json_encode($dto)`. ## Serializable ### Description Enables the Serializable interface for `serialize($dto)` and `unserialize($dto)` methods. ## Stringable ### Description Enables the Stringable interface for treating the DTO as a string (`(string)$dto`). ``` -------------------------------- ### onAssigning Source: https://github.com/atlcomgit/dto/blob/master/docs/OVERRIDES.md This method is called before a property's value is changed in the DTO. ```APIDOC ## onAssigning ### Description This method is called before a property's value is changed in the DTO. ### Method Signature `protected function onAssigning(string $key, mixed $value): void` ### Parameters #### Path Parameters - **key** (string) - Description of the property key. - **value** (mixed) - The new value being assigned to the property. ### Response This method does not return a value. ``` -------------------------------- ### Extending DTO Functionality with Traits Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates how to extend DTO functionality by using traits, specifically the `AsDto` trait, to enable DTO capabilities on a class. ```php class CarDto { use AsDto; public string $markName; } $carDto1 = CarDto::create(markName: 'Lexus'); /* Вывод результата */ print_r($carDto->markName); ``` -------------------------------- ### Transforming DTOs with Mappings and Serialization Control Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates transforming one DTO into another, including handling property name mappings and controlling which properties are included during serialization. This is useful for data conversion and API versioning. ```php class CarFirstDto extends \Atlcom\Dto { public string $markName; public string $modelName; protected function mappings(): array { return [ 'modelName' => 'model_name', ]; } } class CarSecondDto extends \Atlcom\Dto { public string $markName; public string $modelName; public int $year; } class CarThirdDto extends \Atlcom\Dto { public string $markName; public string $modelName; public int $year; protected function mappings(): array { return [ 'markName' => 'mark_name', ]; } protected function onSerializing(array &$array): void { $this->onlyKeys(['year']); } } $carFirstDto = CarFirstDto::create([ 'markName' => 'Lexus', 'modelName' => 'RX500', ]); $carSecondDto = $carFirstDto->transformToDto(CarSecondDto::class, ['year' => 2024]); $carThirdDto = CarThirdDto::create([ 'markName' => 'Lexus', 'modelName' => 'RX500', 'year' => 2024, ]); $carFirstDto = $carThirdDto->transformToDto(CarFirstDto::class); /* Вывод результата */ print_r($carFirstDto->toArray()); print_r($carSecondDto->toArray()); ``` -------------------------------- ### onFilling(array &$array) Source: https://github.com/atlcomgit/dto/blob/master/README.md Hook method called before filling the DTO with data. ```APIDOC ## onFilling(array &$array) ### Description Hook method called before filling the DTO with data. ### Method protected ### Parameters - **array** (array) - The data array to be used for filling the DTO. ### Response void ``` -------------------------------- ### onCreating() / onCreated() Hooks for DTO Creation Source: https://context7.com/atlcomgit/dto/llms.txt Use `onCreating()` to modify input data before it's used to populate the DTO. `onCreated()` is called after the DTO is populated, allowing for final adjustments to its properties. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $source = 'unknown'; protected function onCreating(mixed &$data): void { // Нормализуем ключ до заполнения if (is_array($data) && isset($data['mark'])) { $data['markName'] = $data['mark']; unset($data['mark']); } } protected function onCreated(mixed $data): void { $this->source = 'created'; } } $dto = CarDto::create(['mark' => 'Toyota']); print_r($dto->toArray()); // ['markName' => 'Toyota', 'source' => 'created'] ``` -------------------------------- ### Dto Creation and Filling Methods Source: https://github.com/atlcomgit/dto/blob/master/README.md Methods for creating and populating DTO objects from various data sources. ```APIDOC ## create ### Description Creates a Dto object from the provided named arguments / associative array / object / JSON string. ### Method `public static create(mixed ...$data)` ``` ```APIDOC ## fill ### Description Creates a Dto object from the provided associative array. ### Method `public static fill(array $data)` ``` ```APIDOC ## collect ### Description Converts an array or collection of data into a collection of dtos. ### Method `public static collect(array $items)` ``` ```APIDOC ## fillFromArray ### Description Fills the Dto object from the provided associative array. ### Method `public fillFromArray(array $data)` ``` ```APIDOC ## fillFromData ### Description Fills the Dto object from the provided associative array / object / JSON string. ### Method `public fillFromData(mixed $data)` ``` ```APIDOC ## fillFromObject ### Description Fills the Dto object from an object with public properties. ### Method `public fillFromObject(array $data)` ``` ```APIDOC ## fillFromDto ### Description Fills the Dto object from another Dto object with public properties. ### Method `public fillFromDto(self $data)` ``` ```APIDOC ## fillFromJson ### Description Fills the Dto object from a JSON string. ### Method `public fillFromJson(self $data)` ``` ```APIDOC ## merge ### Description Merges the Dto object with the provided associative array. ### Method `public merge(object $data)` ``` ```APIDOC ## clear ### Description Clears all properties of the Dto. ### Method `public clear()` ``` ```APIDOC ## transformToDto ### Description Transforms the Dto object into an object of another Dto class and supplements it with data from an array. ### Method `public transformToDto(string $dtoClass, array $array = [])` ``` ```APIDOC ## isEmpty ### Description Checks if the Dto has at least one property filled. ### Method `public isEmpty()` ``` ```APIDOC ## getProperties ### Description Returns an array of Dto properties. ### Method `public static getProperties()` ``` ```APIDOC ## getPropertiesWithFirstType ### Description Returns an array of all Dto properties with their first type. ### Method `public static getPropertiesWithFirstType()` ``` ```APIDOC ## getPropertiesWithAllTypes ### Description Returns an array of all Dto properties with all their types. ### Method `public static getPropertiesWithAllTypes()` ``` -------------------------------- ### Attaching Custom Metadata with customOptions() Source: https://context7.com/atlcomgit/dto/llms.txt Attach arbitrary metadata to DTO objects that does not affect their properties using `customOptions()`, `setCustomOption()`, and `getCustomOption()`. This is useful for storing contextual information. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; } $dto = CarDto::create() ->customOptions(['source' => 'api', 'version' => 2]) ->setCustomOption('locale', 'ru'); print_r($dto->getOption('customOptions')); // ['source' => 'api', 'version' => 2] echo $dto->getCustomOption('locale'); // 'ru' ``` -------------------------------- ### Fill DTO from array or object Source: https://github.com/atlcomgit/dto/blob/master/README.md Instantiate a DTO using `create` with an array or object, or use the `fillFromArray`/`fillFromObject` methods on an existing instance. ```php $exampleDto = ExampleDto::create(['a' => 1, 'b' => 2]); $exampleDto = (new ExampleDto())->fillFromArray(['a' => 1, 'b' => 2]); $exampleDto = ExampleDto::create((object)['a' => 1, 'b' => 2]); $exampleDto = (new ExampleDto())->fillFromObject((object)['a' => 1, 'b' => 2]); $exampleDto = ExampleDto::create('{"a": 1, "b": 2}'); $exampleDto = (new ExampleDto())->fillFromJson('{"a": 1, "b": 2}'); ``` -------------------------------- ### Fill DTO with Nested DTOs, Mapped Properties, and Serialization Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Combine nested DTOs, property mapping using `mappings`, and serialization using `serializeKeys` for complex data structures. This allows for flexible input data handling and controlled output serialization. ```php class MarkDto extends \Atlcom\Dto { public int $id; public string $markName; protected function mappings(): array { return [ 'markName' => 'name', ]; } } class ModelDto extends \Atlcom\Dto { public int $id; public string $modelName; protected function mappings(): array { return [ 'modelName' => 'name', ]; } } class CarDto extends \Atlcom\Dto { public MarkDto $markDto; public ModelDto $modelDto; protected function casts(): array { return [ 'markDto' => MarkDto::class, 'modelDto' => ModelDto::class, ]; } protected function mappings(): array { return [ 'markDto' => 'mark', 'modelDto' => 'model', ]; } } $carDto = CarDto::create([ 'mark' => [ 'id' => 1, 'name' => 'Lexus', ], 'model' => [ 'id' => 2, 'name' => 'RX500', ], ]); /* Вывод результата */ print_r($carDto->serializeKeys()->toArray()); ``` -------------------------------- ### fill() / fillFromArray() - Filling DTOs from Arrays Source: https://context7.com/atlcomgit/dto/llms.txt `fill()` is a static alias for creating a DTO from an array, while `fillFromArray()` is an instance method used to populate an existing DTO object with data from an array. `fillFromArray()` supports auto-mapping for snake_case to camelCase properties. ```APIDOC ## fill() / fillFromArray() - Filling DTOs from Arrays ### Description `fill()` is a static alias for creating a DTO from an array. `fillFromArray()` is an instance method to populate an existing DTO object with data from an array. `fillFromArray()` supports auto-mapping for snake_case to camelCase properties. ### Methods `static fill(array $data) ` `fillFromArray(array $data) ``` -------------------------------- ### Enabling Dynamic Properties with AUTO_DYNAMIC_PROPERTIES_ENABLED Source: https://context7.com/atlcomgit/dto/llms.txt When `AUTO_DYNAMIC_PROPERTIES_ENABLED` is set to `true`, DTOs can accept fields not explicitly declared as class properties. This allows for flexible data structures. ```php class FlexDto extends \Atlcom\Dto { public const AUTO_DYNAMIC_PROPERTIES_ENABLED = true; } $dto = FlexDto::create(name: 'Ivan', role: 'admin', score: 99); echo $dto->name; // 'Ivan' echo $dto->role; // 'admin' echo $dto->score; // 99 ``` -------------------------------- ### Handling DTO Property Assignment Events Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Illustrates how to use the `onAssigned` method to trigger actions after a DTO property has been assigned a new value. This is useful for maintaining internal state or performing calculations based on property changes. ```php class SumDto extends \Atlcom\Dto { protected int $x; protected int $y; protected int $sum = 0; protected function onAssigned(string $key): void { $this->sum = ($this->x ?? 0) + ($this->y ?? 0); } } $sumDto = SumDto::create(x: 1, y: 2); /* Вывод результата */ print_r($sumDto->withProtectedKeys(true)->toArray()); ``` -------------------------------- ### Enable Auto-Mapping for DTO Creation Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Use `AUTO_MAPPINGS_ENABLED = true` to automatically map snake_case keys from an array to camelCase properties during DTO creation. ```php class CarDto extends \Atlcom\Dto { public const AUTO_MAPPINGS_ENABLED = true; public string $markName; public string $modelName; } $carDto = CarDto::create([ 'mark_name' => 'Lexus', 'model_name' => 'RX500', ]); /* Вывод результата */ print_r($carDto->toArray()); ``` -------------------------------- ### Reset all options with `withoutOptions()` Source: https://context7.com/atlcomgit/dto/llms.txt Use `withoutOptions()` to clear all previously set serialization options. This is useful when options are set within a hook like `onSerializing()` but need to be overridden externally. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; protected function onSerializing(array &$array): void { $this->onlyKeys('markName'); // By default - only markName } } // Override: get all fields print_r(CarDto::create()->withoutOptions()->toArray()); // ['markName' => 'Lexus', 'modelName' => 'RX500'] ``` -------------------------------- ### Populating DTOs with Arrays of Objects Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Demonstrates how to populate DTO properties that are arrays of objects using the `casts` method or the `Collection` attribute. This is useful for handling nested data structures. ```php class MarkDto extends \Atlcom\Dto { public int $id; public string $markName; } class ModelDto extends \Atlcom\Dto { public int $id; public string $modelName; } class CarDto extends \Atlcom\Dto { /** @var array */ public array $markNames; /** @var array */ #[Atlcom\Attributes\Collection(ModelDto::class)] public array $modelNames; protected function casts(): array { return [ 'markNames' => [MarkDto::class], ]; } } $array = [ 'markNames' => [ ['id' => 1, 'markName' => 'Lexus'], ['id' => 2, 'markName' => 'Toyota'], ], 'modelNames' => [ ['id' => 3, 'modelName' => 'RX500'], ['id' => 4, 'modelName' => 'RAV4'], ], ]; $carDto = CarDto::create($array); /* Вывод результата */ print_r($carDto->toArray()); ``` -------------------------------- ### Fill DTO from array using fill() or fillFromArray() Source: https://context7.com/atlcomgit/dto/llms.txt The `fill()` static method creates a DTO from an array. The `fillFromArray()` instance method populates an existing DTO, supporting auto-mapping for snake_case properties when enabled. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; } // Статическое создание $dto = CarDto::fill(['markName' => 'Lexus', 'modelName' => 'RX500']); // Заполнение экземпляра (с включённым autoMappings для snake_case) $dto = (new CarDto())->autoMappings()->fillFromArray([ 'mark_name' => 'Lexus', 'model_name' => 'RX500', ]); print_r($dto->toArray()); // ['markName' => 'Lexus', 'modelName' => 'RX500'] ``` -------------------------------- ### Exclude Specific Keys with excludeKeys() Source: https://context7.com/atlcomgit/dto/llms.txt Use the `excludeKeys()` fluent method to specify which properties should be excluded from the serialized output. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; public int $year = 2024; } print_r(CarDto::create()->excludeKeys(['year'])->toArray()); ``` -------------------------------- ### mappings() Source: https://github.com/atlcomgit/dto/blob/master/README.md Defines an array of property names for mapping to other properties. ```APIDOC ## mappings() ### Description Defines an array of property names for mapping to other properties. ### Method protected ### Parameters None ### Response - array - An array of property names for mapping. ``` -------------------------------- ### Serialize Only Specific Keys with onlyKeys() Source: https://context7.com/atlcomgit/dto/llms.txt Use the `onlyKeys()` fluent method to specify which properties should be included in the serialized output. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; public int $year = 2024; } print_r(CarDto::create()->onlyKeys(['markName', 'year'])->toArray()); ``` -------------------------------- ### Use DTO Trait Source: https://github.com/atlcomgit/dto/blob/master/README.md Alternatively, use the \Atlcom\Traits\AsDto trait to enable DTO functionality within your class. ```php class MyDto { use \Atlcom\Traits\AsDto; } ``` -------------------------------- ### exceptions(string $messageCode, array $messageItems) Source: https://github.com/atlcomgit/dto/blob/master/README.md Returns an error message based on its code when working with DTOs. ```APIDOC ## exceptions(string $messageCode, array $messageItems) ### Description Returns an error message based on its code when working with DTOs. ### Method protected ### Parameters - **messageCode** (string) - The code of the error message. - **messageItems** (array) - Additional items for the error message. ### Response - string - The formatted error message. ``` -------------------------------- ### Serialize DTO to Array with mappingKeys Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Use mappingKeys to rename properties during serialization, allowing for custom key names in the output array. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; } $carDto = CarDto::create(); /* Вывод результата */ print_r($carDto->mappingKeys(['markName' => 'mark_name'])->toArray()); print_r($carDto->mappingKeys(['markName' => 'Марка', 'modelName' => 'Модель'])->toArray()); ``` -------------------------------- ### Add Custom Options to DTO with customOptions Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Adds custom options to a DTO and retrieves their values. Multiple calls to customOptions will merge the options. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; } $carDto = CarDto::create() ->customOptions(['firstOption' => 1]) ->customOptions(['secondOption' => 2]) ; /* Вывод результата */ print_r($carDto->getOption('customOptions')); ``` -------------------------------- ### Serialize for a specific entity with `for()` Source: https://context7.com/atlcomgit/dto/llms.txt Use the `for()` method to automatically select and name fields for compatibility with a specified entity class. This method infers the required fields and their names based on the target entity's structure. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; protected function mappings(): array { return ['modelName' => 'model_name']; } } class CarEntity { public string $model_name; } print_r(CarDto::create()->for(CarEntity::class)->toArray()); // ['model_name' => 'RX500'] ``` -------------------------------- ### DTO Filling with onFilled Event Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Illustrates the use of the `onFilled` event to modify DTO properties after they have been populated. This event allows for post-population adjustments. ```php class CarDto extends \Atlcom\Dto { public ?string $markName; public ?string $modelName; protected function onFilled(array $array): void { $this->markName = 'Lexus'; $this->modelName = 'RX500'; } } $carDto = CarDto::create(); /* Вывод результата */ print_r($carDto->toArray()); ``` -------------------------------- ### includeStyles() Source: https://context7.com/atlcomgit/dto/llms.txt Adds camelCase and snake_case variants of keys to the serialized output. This is useful for compatibility with different naming conventions. ```APIDOC ## includeStyles() ### Description Adds camelCase and snake_case variants of keys to the serialized output. This is useful for compatibility with different naming conventions. ### Method `includeStyles()` ### Request Example ```php print_r(CarDto::create()->includeStyles()->toArray()); ``` ### Response Example ```json { "markName": "Lexus", "modelName": "RX500", "mark_name": "Lexus", "model_name": "RX500" } ``` ``` -------------------------------- ### getProperties() / getPropertiesWithFirstType() / getPropertiesWithAllTypes() Source: https://context7.com/atlcomgit/dto/llms.txt Introspects the DTO to retrieve information about its properties, including their names and types. ```APIDOC ## getProperties() / getPropertiesWithFirstType() / getPropertiesWithAllTypes() ### Description Introspects the DTO to retrieve information about its properties, including their names and types. ### Method `getProperties()` `getPropertiesWithFirstType()` `getPropertiesWithAllTypes()` ### Request Example ```php // Get property names print_r(CarDto::getProperties()); // Get property names with their first declared type print_r(CarDto::getPropertiesWithFirstType()); // Get property names with all declared types (including null) print_r(CarDto::getPropertiesWithAllTypes()); ``` ### Response Example ```json // For getProperties() [ "markName", "year", "color" ] // For getPropertiesWithFirstType() { "markName": "string", "year": "int", "color": "string" } // For getPropertiesWithAllTypes() { "markName": ["string"], "year": ["int", "null"], "color": ["string", "null"] } ``` ``` -------------------------------- ### Map Input Keys to DTO Properties Source: https://context7.com/atlcomgit/dto/llms.txt The `mappings()` method defines the correspondence between DTO property names and input array keys. It supports dot notation for nested arrays. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; public int $manufacturingYear; protected function mappings(): array { return [ 'markName' => 'mark_name', // snake_case → camelCase 'modelName' => 'model.name', // вложенный ключ через точку 'manufacturingYear' => 'details.year', ]; } } $dto = CarDto::create([ 'mark_name' => 'Lexus', 'model' => ['name' => 'RX500'], 'details' => ['year' => 2024], ]); print_r($dto->toArray()); // ['markName' => 'Lexus', 'modelName' => 'RX500', 'manufacturingYear' => 2024] ``` -------------------------------- ### onAssigned(string $key) Source: https://github.com/atlcomgit/dto/blob/master/README.md Hook method called after the value of a DTO property has been changed. Requires PROTECTED or PRIVATE visibility for the property. ```APIDOC ## onAssigned(string $key) ### Description Hook method called after the value of a DTO property has been changed. Requires PROTECTED or PRIVATE visibility for the property. ### Method protected ### Parameters - **key** (string) - The key of the property that was assigned. ### Response void ``` -------------------------------- ### Nested DTO Creation and Casting Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Shows how to create DTOs with nested DTO structures. The `casts` method is used to explicitly define how nested properties should be cast to their respective DTO classes. ```php class CarDto1 extends \Atlcom\Dto { public string $markName; public CarDto2 $carDto2; public CarDto2 $carDto3; protected function casts(): array { return [ 'carDto3' => CarDto2::class, ]; } } class CarDto2 extends \Atlcom\Dto { public string $markName; protected function onCreated(mixed $data): void { $this->markName = 'Toyota'; } } $carDto1 = CarDto1::create( markName: 'Lexus', carDto2: CarDto2::create(markName: 'Lexus'), carDto3: ['markName' => 'Lexus'], ); /* Вывод результата */ print_r($carDto1->toArray()); ``` -------------------------------- ### Fill DTO with Mapping from Multilevel Array Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Use the `mappings` method to specify how to populate DTO properties from nested array keys. This is useful when the source data structure differs from the DTO structure. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; protected function mappings(): array { return [ 'markName' => 'mark.name', 'modelName' => 'model.name', ]; } } $carDto = CarDto::create([ 'mark' => [ 'name' => 'Lexus', ], 'model' => [ 'name' => 'RX500', ], ]); /* Вывод результата */ print_r($carDto->toArray()); ``` -------------------------------- ### Prepare DTO for a specific entity Source: https://github.com/atlcomgit/dto/blob/master/README.md Use the `for` method to prepare DTO properties for a given entity instance or class name before serialization. ```php $carEntity = new CarEntity(); $exampleDto = ExampleDto::create(); $exampleArray = $exampleDto->for($carEntity)->toArray(); $exampleArray = $exampleDto->for(CarEntity::class)->toArray(); ``` -------------------------------- ### Fill DTO from Array with Auto-Mapping Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Use the `autoMappings()` method before `fillFromArray()` to enable automatic mapping of snake_case array keys to camelCase DTO properties. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; } $carDto = (new CarDto())->autoMappings()->fillFromArray([ 'mark_name' => 'Lexus', 'model_name' => 'RX500', ]); /* Вывод результата */ print_r($carDto->toArray()); ``` -------------------------------- ### Customizing DTO Exception Messages Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Shows how to override the `exceptions` method to provide custom error messages when DTO creation or manipulation fails. This allows for more user-friendly error reporting. ```php class CarDto extends \Atlcom\Dto { public string $markName; public string $modelName; protected function exceptions(string $messageCode, array $messageItems): string { return 'Текст ошибки'; } } try { $carDto = CarDto::create(); } catch (Exception $e) { $exceptionMessage = $e->getMessage(); } /* Вывод результата */ print_r([$exceptionMessage]); ``` -------------------------------- ### onException(Throwable $exception) Source: https://github.com/atlcomgit/dto/blob/master/README.md Hook method called before an exception is thrown. Requires PROTECTED or PRIVATE visibility for the property. ```APIDOC ## onException(Throwable $exception) ### Description Hook method called before an exception is thrown. Requires PROTECTED or PRIVATE visibility for the property. ### Method protected ### Parameters - **exception** (Throwable) - The exception object. ### Response void ``` -------------------------------- ### Convert DTO to Array of Properties with Types Source: https://github.com/atlcomgit/dto/blob/master/docs/EXAMPLES.md Returns an array of all DTO properties and their associated types. getPropertiesWithFirstType() returns only the first type if multiple are specified. ```php class CarDto extends \Atlcom\Dto { public ?string $markName; } $carArray = CarDto::getProperties(); $carArray2 = CarDto::getPropertiesWithFirstType(); /* Вывод результата */ print_r($carArray); print_r($carArray2); ``` -------------------------------- ### Include camelCase and snake_case variants with `includeStyles()` Source: https://context7.com/atlcomgit/dto/llms.txt Use `includeStyles()` to automatically include both camelCase and snake_case versions of property names in the serialized output. This is useful for compatibility with systems that expect different naming conventions. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; public string $modelName = 'RX500'; } print_r(CarDto::create()->includeStyles()->toArray()); // ['markName' => 'Lexus', 'modelName' => 'RX500', 'mark_name' => 'Lexus', 'model_name' => 'RX500'] ``` -------------------------------- ### Extend DTO Class Source: https://github.com/atlcomgit/dto/blob/master/README.md To implement DTO functionality, extend the \Atlcom\Dto class. ```php class MyDto extends \Atlcom\Dto {} ``` -------------------------------- ### Serialization Methods (Array/JSON Conversion) Source: https://github.com/atlcomgit/dto/blob/master/README.md Methods for serializing DTO objects into arrays or JSON strings. ```APIDOC ## toArray ### Description Serializes the Dto into an array. ### Method `public toArray(?bool $onlyFilled = null)` ``` ```APIDOC ## toArrayBlank ### Description Returns an array with empty values for all Dto properties. ### Method `public static toArrayBlank()` ``` ```APIDOC ## toArrayBlankRecursive ### Description Returns an array with empty values for all Dto properties, recursively traversing objects. ### Method `public static toArrayBlankRecursive()` ``` ```APIDOC ## toJson ### Description Serializes the Dto into a JSON string. ### Method `public toJson($options = 0)` ``` -------------------------------- ### DTO Serialization Options Source: https://github.com/atlcomgit/dto/blob/master/README.md Chain serialization options like `onlyKeys`, `excludeKeys`, `mappingKeys`, and `serializeKeys` before converting the DTO to an array. Note that these options reset after `toArray()` or `toJson()`. ```php $exampleDto = ExampleDto::fill(['a' => 1, 'c' => 3]) ->merge(['b' => 2]); $exampleArray = $exampleDto ->onlyKeys(['a', 'b']) ->excludeKeys(['c']) ->mappingKeys(['a' => 'aa', 'b' => 'bb']) ->serializeKeys(['a', 'b']) ->toArray(); ``` -------------------------------- ### collect() - Creating a Collection of DTOs Source: https://context7.com/atlcomgit/dto/llms.txt The `collect()` static method transforms an array of data into an array of DTO objects of a specified class. This is convenient for handling lists of structured data. ```APIDOC ## collect() - Creating a Collection of DTOs ### Description Transforms an array of data into an array of DTO objects of a specified class. This is convenient for handling lists of structured data. ### Method `static collect(array $items) ``` -------------------------------- ### Add arbitrary keys to the result with `includeArray()` Source: https://context7.com/atlcomgit/dto/llms.txt The `includeArray()` method allows you to add custom key-value pairs to the serialized output. This is helpful for including data that is not directly represented by DTO properties. ```php class CarDto extends \Atlcom\Dto { public string $markName = 'Lexus'; } print_r(CarDto::create()->includeArray(['modelName' => 'RX500', 'year' => 2024])->toArray()); // ['markName' => 'Lexus', 'modelName' => 'RX500', 'year' => 2024] ```