Skip to content

Instantly share code, notes, and snippets.

@Davenchy
Last active May 3, 2024 03:09
Show Gist options
  • Save Davenchy/99d5ec6ca630ba536fc6f3a355ce52d2 to your computer and use it in GitHub Desktop.
Save Davenchy/99d5ec6ca630ba536fc6f3a355ce52d2 to your computer and use it in GitHub Desktop.
PHP User Model
class User {
private $id;
private $name;
private $email;
public function __construct(int $id, string $name, string $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
public function getId(): int {
return $this->id;
}
public function getName(): string {
return $this->name;
}
public function getEmail(): string {
return $this->email;
}
public function copyWith(array $updates): self {
$props = [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email
];
foreach ($updates as $key => $value) {
if (array_key_exists($key, $props)) {
$props[$key] = $value;
}
}
return new self($props['id'], $props['name'], $props['email']);
}
public static function getById(int $id) {
// Code to fetch user from the database
$user = getUserFromDatabase($id); // Placeholder function, replace with actual implementation
return new self($user['id'], $user['name'], $user['email']);
}
public function commit() {
// Code to update user in the database
updateUserInDatabase($this->id, $this->name, $this->email); // Placeholder function, replace with actual implementation
}
public function toJSON(): string {
return json_encode([
'id' => $this->id,
'name' => $this->name,
'email' => $this->email
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment