Home Quizzes Leaderboard Competitions Learn Hire Us
About Contact
Log In Sign Up
Learn PHP Design Patterns

Design Patterns

⏱ 22 min read read
1. Singleton Pattern:

Ensures only ONE instance of a class exists. Useful for database
connections, config, loggers.

class AppConfig {

private static ?AppConfig $instance = null;

private array $settings = [];

private function \_\_construct() {

$this->settings['db_url'] = 'mysql://localhost/mydb';

}

public static function getInstance(): self {

if (self::$instance === null) {

self::$instance = new self();

}

return self::$instance;

}

public function get(string $key): mixed {

return $this->settings[$key] ?? null;

}

}

$c1 = AppConfig::getInstance();

$c2 = AppConfig::getInstance();

var_dump($c1 === $c2); // bool(true) --- same object!

2. Builder Pattern:

Constructs complex objects step-by-step with method chaining (return
$this).

class QueryBuilder {

private string $table = '';

private array $conditions = [];

private ?int $limit = null;

public function from(string $table): self { $this->table =
$table; return $this; }

public function where(string $cond): self { $this->conditions[]
= $cond; return $this; }

public function limit(int $n): self { $this->limit = $n; return
$this; }

public function build(): string {

$sql = "SELECT * FROM {$this->table}";

if ($this->conditions) $sql .= ' WHERE ' . implode(' AND ',
$this->conditions);

if ($this->limit !== null) $sql .= " LIMIT {$this->limit}";

return $sql;

}

}

$sql = (new QueryBuilder())->from('users')->where('age >
18')->limit(10)->build();

3. Observer Pattern:

Objects subscribe to events. When something happens, all subscribers are
notified.
Code Example
<?php

// 1. SINGLETON

class AppConfig {

private static ?self $instance = null;

private array $settings = ['db_url' =>
'mysql://localhost/mydb'];

private function \_\_construct() {}

private function \_\_clone() {}

public static function getInstance(): self {

if (self::$instance === null) {

self::$instance = new self();

}

return self::$instance;

}

public function get(string $key): mixed { return
$this->settings[$key] ?? null; }

}

$c1 = AppConfig::getInstance();

$c2 = AppConfig::getInstance();

var_dump($c1 === $c2); // bool(true) --- same object

echo $c1->get('db_url') . "\n";

// 2. BUILDER --- method chaining

class Pizza {

private string $size = 'Medium';

private string $crust = 'Thin';

private bool $cheese = false;

private bool $pepperoni = false;

public function size(string $s): static { $this->size = $s;
return $this; }

public function crust(string $c): static { $this->crust = $c;
return $this; }

public function cheese(): static { $this->cheese = true; return
$this; }

public function pepperoni(): static { $this->pepperoni = true;
return $this; }

public function \_\_toString(): string {

$toppings = array_filter([

$this->cheese ? 'cheese' : null,

$this->pepperoni ? 'pepperoni' : null,

]);

return "{$this->size} {$this->crust} crust pizza with " .
implode(', ', $toppings);

}

}

$p = (new
P
izza())->size('Large')->crust('Thin')->cheese()->pepperoni();

echo $p . "\n";

// 3. OBSERVER

interface Observer {

public function update(string $stock, float $price): void;

}

class StockMarket {

private array $observers = [];

public function subscribe(Observer $obs): void {
$this->observers[] = $obs; }

public function setPrice(string $stock, float $price): void {

foreach ($this->observers as $obs) {

$obs->update($stock, $price);

}

}

}

class AlertObserver implements Observer {

public function update(string $stock, float $price): void {

echo "Alert: $stock = \$$price\n";

}

}

class SellObserver implements Observer {

public function update(string $stock, float $price): void {

if ($price > 200) echo "SELL $stock!\n";

}

}

$market = new StockMarket();

$market->subscribe(new AlertObserver());

$market->subscribe(new SellObserver());

$market->setPrice('AAPL', 180.50);

$market->setPrice('GOOG', 210.00);

?>
← Working with Dates & Time Final Project --- Student Management Sys →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress