Skip to content

Instantly share code, notes, and snippets.

@boesing
Last active March 11, 2025 14:27
Show Gist options
  • Save boesing/30fd202cb257e53fc2d4ea3d5c129bd4 to your computer and use it in GitHub Desktop.
Save boesing/30fd202cb257e53fc2d4ea3d5c129bd4 to your computer and use it in GitHub Desktop.
<?php
class User
{
// Resolution access could change to readonly to make object immutable
public string $id;
public string $firstName;
public string $lastName;
public function __construct(string $id, string $firstName, ?string $lastName)
{
$this->id = $id;
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
class Database
{
public static function query($query, $id) {
// ... database returns $row
return new User($row['id'], $row['firstName'], $row['lastName']);
}
}
class UserDatabase extends Database
{
public static function findUsers($ids) {
foreach ($ids as $id) {
$results[] = UserDatabase::findById($id);
}
return $results;
}
public static function findById($id) {
return Database::query("SELECT `firstName`,`lastName` FROM `users` WHERE `id`=" . $id, $id);
}
}
class UserService {
public function findUsers($ids) {
$users = UserDatabase::findUsers($ids);
if($users == null) {
throw new Exception('Users not found!');
}
return $users;
}
}
$userService = new UserService();
class Application {
public function run(){
$users = $userService->findUsers([1, 2, 3]);
foreach ($users as $user) {
var_dump($user->id);
var_dump($user->firstName);
var_dump($user->lastName);
}
}
}
$application = new Application();
$application->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment