File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ Lazy Data
2+ =
3+
4+ Out of the box, extending ` Data ` will give you the ability to create [ Lazy objects] ( https://www.php.net/manual/en/language.oop5.lazy-objects.php ) .
5+ You can achieve that by calling either ` createLazy ` or ` createLazyUsing ` methods, depending
6+ on whether you want to pass properties from the get-go or not.
7+
8+ Let's take for example ` UserData ` class:
9+
10+ ``` php
11+ use Nuxtifyts\PhpDto\Data;
12+
13+ final readonly class UserData extends Data
14+ {
15+ public function __construct(
16+ public int $id,
17+ public string $firstName,
18+ public string $lastName
19+ ) {}
20+ }
21+ ```
22+
23+ We can create a lazy object like this:
24+
25+ ``` php
26+ $user = UserData::createLazy(
27+ id: 1,
28+ firstName: 'John',
29+ lastName: 'Doe'
30+ );
31+ ```
32+
33+ Or, if we have more complex logic to run before creating the object, we can do:
34+
35+ ``` php
36+ // Supposedly, we know the user id.
37+ $userId = 1;
38+
39+ $user = UserData::createLazyUsing(
40+ static function () use($userId): UserData {
41+ // Fetch user data from the database. then create the DTO.
42+ return UserData::from(UserModel::find($userId));
43+ }
44+ )
45+ ```
46+
47+ The ` createLazyUsing ` method accepts a closure that returns the object.
48+ This closure will be called only once, and the object will be cached for future calls.
49+
50+ > For more information about lazy objects. Please refer to the [ PHP documentation] ( https://www.php.net/manual/en/language.oop5.lazy-objects.php ) .
You can’t perform that action at this time.
0 commit comments