Skip to content

Instantly share code, notes, and snippets.

@whchi
Created October 7, 2024 10:25
Show Gist options
  • Select an option

  • Save whchi/20a336551510bf6846779db5c61cd1ed to your computer and use it in GitHub Desktop.

Select an option

Save whchi/20a336551510bf6846779db5c61cd1ed to your computer and use it in GitHub Desktop.
php dto example
<?php
class BaseDto
{
/**
* Constructor that dynamically sets properties based on the given associative array
*
* @param array $data The data to be used for setting properties
*/
public function __construct(array $data)
{
foreach ($data as $key => $value) {
$this->{$key} = $value;
}
}
/**
* Magic method to handle getting properties dynamically
*
* @param string $name The name of the property to get
* @return mixed|null The value of the property if it exists, or null otherwise
*/
public function __get(string $name)
{
return $this->{$name} ?? null;
}
/**
* Magic method to handle setting properties dynamically
*
* @param string $name The name of the property to set
* @param mixed $value The value to set the property to
*/
public function __set(string $name, $value): void
{
$this->{$name} = $value;
}
}
class UserDto extends BaseDto
{
public string $name;
public string $email;
}
// Usage example
$userData = [
'email' => 'john.doe@example.com',
'name' => 'John Doe',
];
$user = new UserDto($userData);
// Accessing properties
echo $user->name; // Output: John Doe
echo $user->email; // Output: john.doe@example.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment