File tree 2 files changed +61
-0
lines changed
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ Empty Data
2
+ =
3
+
4
+ Sometimes we may need to create a fresh instance of a DTO without any data,
5
+ and by default ` Data ` classes have the ability to create an ` "empty" ` instance:
6
+
7
+ ``` php
8
+ use Nuxtifyts\PhpDto\Data;
9
+ use DateTimeImmutable;
10
+
11
+ final reaconly class Todo extends Data
12
+ {
13
+ public function __construct(
14
+ public string $title,
15
+ public string $content,
16
+ public Status $status,
17
+ public ?DateTimeImmutable $dueDate
18
+ ) {}
19
+ }
20
+ ```
21
+
22
+ The ` Status ` enum is defined as follows:
23
+
24
+ ``` php
25
+ enum Status: string
26
+ {
27
+ case DEFAULT = 'default';
28
+ case DONE = 'done';
29
+ case CANCELED = 'canceled';
30
+ }
31
+ ```
32
+
33
+ By calling the ` empty() ` method, we can create a new instance of the ` Todo ` class with all properties set to ` null ` :
34
+
35
+ ``` php
36
+ $emptyTodo = Todo::empty();
37
+ ```
38
+
39
+ The ` $emptyTodo ` variable will contain the following data:
40
+
41
+ ```
42
+ [
43
+ 'title' => '',
44
+ 'comtent' => '',
45
+ 'status' => Status::DEFAULT,
46
+ 'dueDate' => null
47
+ ]
48
+ ```
49
+
50
+ This is useful when we want to gradually fill in the data of a DTO instance,
51
+ here is a list of the empty values for each type:
52
+
53
+ - ` NULL ` : ` null ` (Null takes priority over everything)
54
+ - ` STRING ` : ` '' `
55
+ - ` INT ` : ` 0 `
56
+ - ` FLOAT ` : ` 0.0 `
57
+ - ` BOOLEAN ` : ` false `
58
+ - ` ARRAY ` : ` [] ` (Any type of array will default to an empty one)
59
+ - ` DATETIME ` : New instance of DateTime/DateTimeImmutable
60
+ - ` BACKEDENUM ` : First case of the enum
Original file line number Diff line number Diff line change @@ -80,3 +80,4 @@ can be found here:
80
80
- [ Normalizers] ( https://github.com/nuxtifyts/php-dto/blob/main/docs/Normalizers.md )
81
81
- [ Property Attributes] ( https://github.com/nuxtifyts/php-dto/blob/main/docs/PropertyAttributes.md )
82
82
- [ Data Refiners] ( https://github.com/nuxtifyts/php-dto/blob/main/docs/DataRefiners.md )
83
+ - [ Empty Data] ( https://github.com/nuxtifyts/php-dto/blob/main/docs/EmptyData.md )
You can’t perform that action at this time.
0 commit comments