Skip to content

Instantly share code, notes, and snippets.

@ilzrv
Last active May 3, 2020 11:13
Show Gist options
  • Save ilzrv/4dbc6bf9607f791fdeea7d6788d3bac1 to your computer and use it in GitHub Desktop.
Save ilzrv/4dbc6bf9607f791fdeea7d6788d3bac1 to your computer and use it in GitHub Desktop.
Data Transfer Object (DTO) in Laravel with PHP7.4 typed properties. Source: https://dev.to/zubairmohsin33/data-transfer-object-dto-in-laravel-with-php7-4-typed-properties-2hi9
<?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];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment