https://github.com/gotocva/dto-in-laravel
https://github.com/gotocva/dto-in-laravel
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/gotocva/dto-in-laravel
- Owner: gotocva
- Created: 2021-02-11T04:48:03.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2021-02-11T04:51:43.000Z (over 5 years ago)
- Last Synced: 2025-01-18T11:29:12.881Z (over 1 year ago)
- Size: 1000 Bytes
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# DTO-in-laravel
Data Transfer Objects help in "structuring" the data coming from different types of requests ( Http request, Webhook request etc. ) into single form which we can use in various parts of our application. With DTOs, we have confidence that we will not get unexpected data in our application logic.
```
NOTE: Below code is valid only for PHP 7.4
```
```php
class CheckoutData extends DataTransferObject
{
public int $checkout_id;
public Carbon $completed_at;
public static function fromRequest(Request $request){ ... }
public static function fromWebhook(array $params)
{
return new self([
'checkout_id' => $params['id'],
'completed_at' => $params['completed_at']
]);
}
}
```
```php
abstract class DataTransferObject
{
public function __construct(array $parameters = [])
{
$class = new ReflectionClass(static::class);
foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $reflectionProperty){
$property = $reflectionProperty->getName();
$this->{$property} = $parameters[$property];
}
}
}
```
This is how we can easily construct our Data Transfer Objects with PHP7.4.