Skip to content

Instantly share code, notes, and snippets.

@mcsee
Created February 3, 2026 21:53
Show Gist options
  • Select an option

  • Save mcsee/b31a828edad3e8b019e7fc2217c1f5c4 to your computer and use it in GitHub Desktop.

Select an option

Save mcsee/b31a828edad3e8b019e7fc2217c1f5c4 to your computer and use it in GitHub Desktop.
This gist belongs to the Clean Code Cookbook https://cleancodecookbook.com by Maximiliano Contieri https://maximilianocontieri.com
<?
class UserDirectory {
// 1. Create a new class to represent the specific collection
// This is a real world concept reified
// 2. Define a private property
private array $elements = [];
// 3. Implement a constructor that accepts only User types
public function __construct(User ...$users) {
$this->elements = $users;
}
// 4. Add type-hinted methods to add elements
public function add(User $user): void {
$this->elements[] = $user;
}
// 5. Move collection-specific logic inside
public function notifyAll(): void {
foreach ($this->elements as $user) {
$user->sendNotification();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment