Skip to content

Commit 4f2511e

Browse files
author
Яценко Андрей
committed
Initial commit
0 parents  commit 4f2511e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
## Class-transformer function plainToClass
2+
3+
Class-transformer function to transform our object into a typed object
4+
5+
## :scroll: **Installation**
6+
The package can be installed via composer:
7+
```
8+
composer require yzen.dev/plain-to-class
9+
```
10+
11+
## :scroll: **Usage**
12+
Suppose you have a service for authorization. To ensure the reliability of the input data, it would be good to send DTO there:
13+
```php
14+
class AuthService {
15+
public function register(RegisterDTO $data)
16+
{
17+
//crete user...
18+
}
19+
}
20+
```
21+
```php
22+
class RegisterDTO
23+
{
24+
/** @var string Email */
25+
public string $email;
26+
27+
/** @var string Password */
28+
public string $password;
29+
}
30+
```
31+
But then we will have to create an object of this DTO each time:
32+
```php
33+
public function register(RegisterUserRequest $request)
34+
{
35+
$registerDTO = new RegisterDTO();
36+
$registerDTO->email= $request->email;
37+
$registerDTO->password= $request->password;
38+
$this->authService->register($registerDTO);
39+
}
40+
```
41+
For this, this method was created, which will allow you to create an instance DTO without much difficulty.
42+
```php
43+
class AuthController
44+
{
45+
private AuthService $authService;
46+
47+
//...
48+
49+
public function register(RegisterUserRequest $request)
50+
{
51+
$registerDTO = plainToClass(RegisterDTO::class, $request->toArray());
52+
$this->authService->register($registerDTO);
53+
}
54+
```
55+
56+
If the data contains arguments that are not in the class, they will simply be skipped.
57+
58+
```php
59+
$data = [
60+
'email' => 'test',
61+
'password' => '123456',
62+
'fakeField' => 'fake',
63+
];
64+
$dto = plainToClass(LoginDTO::class,$data);
65+
var_dump($dto);
66+
```
67+
Result:
68+
```php
69+
object(\LoginDTO)[298]
70+
public string 'email' => string 'test' (length=4)
71+
public string 'password' => string '123456' (length=6)
72+
```

0 commit comments

Comments
 (0)