Skip to content

Commit 738964c

Browse files
committed
Added documentation on lazy data
1 parent b617258 commit 738964c

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

docs/LazyData.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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).

0 commit comments

Comments
 (0)