Last active
May 3, 2020 11:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'] | |
]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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