@@ -4,6 +4,7 @@ Property Attributes
44In order to provide more functionality to your DTOs, you can use the following attributes:
55- [ Computed] ( #Computed ) - To define a property that is computed from other properties.
66- [ Aliases] ( #Aliases ) - To define aliases for a property.
7+ - [ DefaultsUsing] ( #DefaultsUsing ) - To define a default value for a property using a fallback resolver.
78- [ CipherTarget] ( #CipherTarget ) - To define a property that should be encrypted/decrypted.
89
910Computed
@@ -109,3 +110,48 @@ public function __construct(
109110) {}
110111```
111112
113+ DefaultsUsing
114+ -
115+
116+ Sometimes, we may need to specify that a property has a default value,
117+ we can achieve that using plain PHP for some property types but not all of them.
118+
119+ ``` php
120+ use Nuxtifyts\PhpDto\Data;
121+
122+ final readonly class User extends Data
123+ {
124+ public function __construct(
125+ public string $firstName,
126+ public string $lastName,
127+ public string $email,
128+ public UserType $type = UserType::DEFAULT,
129+ public UserConfigData $config,
130+ ) {}
131+ }
132+ ```
133+
134+ On the other hand, if we want to specify, for example, a default value for UserType depending
135+ on the provided email address, or if you want to provide a default value for complex data such as
136+ ` UserConfigData ` which is another DTO, there is no way to do it using plain PHP,
137+ that's where ` DefaultsUsing ` attribute comes in.
138+
139+ ``` php
140+ use Nuxtifyts\PhpDto\Data;
141+ use Nuxtifyts\PhpDto\Attributes\Property\DefaultsUsing;
142+
143+ final readonly class User extends Data
144+ {
145+ public function __construct(
146+ public string $firstName,
147+ public string $lastName,
148+ public string $email,
149+ #[DefaultsUsing(UserTypeFallbackResolver::class)]
150+ public UserType $type,
151+ #[DefaultsUsing(UserConfigDataFallbackResolver::class)]
152+ public UserConfigData $config,
153+ ) {}
154+ }
155+ ```
156+
157+ TODO - Add example of fall back resolver code
0 commit comments