Skip to content

Instantly share code, notes, and snippets.

View UtmostCreator's full-sized avatar
🎯
Focusing

Roman UtmostCreator

🎯
Focusing
View GitHub Profile
<?php
/*
Intent: treat part and whole uniformly.
- Must have: a common interface (Component) that both Leaf and Composite implement.
- Leaf: implements operations directly (no children).
- Composite: stores children (array of Component) and delegates/aggregates operations to them.
- Child management: add()/remove() live only on Composite (or on Component if you prefer full transparency).
- Client: talks to Component only-no instanceof checks or special-casing.
- Gotcha: keep traversal/iteration inside Composite; don’t leak structure.
<?php
/*
S - One class one purpose, it holds the data & methods needed for its job & nothing more.
Open/Closed Principle
O - open for extension, closed for modification
Liskov Substitution Principle
L - Child classes must be usable in place of their parent classes
Interface Segregation Principle
I - Don't force classes to implement things they don't need
Dependency Inversion Principle
@UtmostCreator
UtmostCreator / Composition principle.php
Last active October 30, 2025 17:01
favor composition over inheritance
<?php
/*
Composition (OO principle: “favor composition over inheritance”)
- Intent: build behavior via has-a relationships; delegate work to contained objects.
- Must do: define small interfaces for roles (e.g., Engine), not concrete classes.
- Inject collaborators (constructor/setter) so they can be swapped (flexibility, testability).
- Delegate from the host to the collaborator ($this->engine->ignite()), don’t subclass just to reuse code.
- Use inheritance sparingly (stable, is-a hierarchies only); prefer composition when behavior varies.
- Smell to avoid: deep hierarchies, protected hacks, or switches to select behavior—extract to collaborators instead.
*/
<?php
/** Strategy interface (family of algorithms) */
interface ValidationRule
{
public function validate(string $value): bool;
}
/** Concrete strategies */
final class EmailRule implements ValidationRule
<?php
/*
Strategy, and how this PHP example implements it:
- Why the name: From GoF—encapsulate interchangeable algorithms (“strategies”) behind a common interface and swap them at runtime.
- Roles here:
• Strategy interface: RouteStrategy::buildRoute(float): string
• Concrete strategies: CarStrategy, BikeStrategy, WalkStrategy, TransitStrategy
• Context: Navigator holds a RouteStrategy
- Mechanics: Navigator uses composition + delegation—buildRoute($km) forwards to the injected strategy. Clients can switch behavior via setStrategy(...) without modifying Navigator.
- Benefits: Open/Closed (add new routing without touching Navigator), removes conditionals, isolates and unit-tests algorithms independently.
<?php
/*
Delegation Pattern
------------------
Intent: An object passes (delegates) a task to a helper object
instead of doing it itself — but keeps the same interface.
Difference from Strategy:
- Strategy = interchangeable algorithms.
- Delegation = same responsibility, but helper *acts on behalf of* the main object.
<?php
final class DB
{
private static ?self $instance = null;
private \PDO $pdo;
private function __construct()
{
$host = $_ENV['DB_HOST'] ?? '127.0.0.1';
@UtmostCreator
UtmostCreator / Singleton.php
Last active October 30, 2025 17:03
most basic example pattern
<?php
/*
Singleton, and how the PHP version enforces it:
- Why the name: From the GoF book—“Ensure a class has only one instance, and provide a global point of access to it.” A singleton set has exactly one element; same idea here.
- Private constructor: `private function __construct()` prevents `new Singleton()` from the outside.
- Single stored instance: a private static property (e.g., `private static ?self $instance`) holds the one-and-only object (and allows this propery to be accessed from static method instance()).
- Global access point: a public static accessor (e.g., `instance()`) lazily creates and returns that object.
- No copies: block duplication by making `__clone()` private and throwing in `__wakeup()` (and, if you like, `__serialize/__unserialize`) to prevent cloning/unserialization.
- No subclasses: mark the class `final` so inheritance can’t sneak in extra instances.
<?php
$odd = [1,3,5,7];
$diff = [1,2,3,4,5];
$even = [2,4,6,8];
// 1 find if all numbers are even
$res = array_all($even, fn($el, $key) => $el % 2 === 0);
// var_dump($res);
// 2 find if any numbers are odd
@UtmostCreator
UtmostCreator / recursion.php
Last active October 30, 2025 17:03
recursion function and its own stack frame
<?php
function rDemo($n, $level = 1): void {
$indent = str_repeat(" ", $level - 1);
echo $indent . ' => Entering level ' . $level . "(n={$n})" . PHP_EOL;
if ($n <= 0) {
echo $indent . "Base case reached at level " . $level . " (n = " . $n . ")" . PHP_EOL;
return;
}
rDemo($n - 1, $level + 1);