Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

Advanced 30 snippets

function resize_jpeg(string $src, string $dest, int $maxWidth = 900, int $quality = 82): bool
{
    [$w, $h, $type] = getimagesize($src) ?: [0, 0, 0];
    if ($type !== IMAGETYPE_JPEG || $w < 1) return false;

    $ratio = min(1, $maxWidth / $w);            // never enlarge
    $nw = (int)round($w * $ratio);
    $nh = (int)round($h * $ratio);

    $in  = imagecreatefromjpeg($src);
    $out = imagecreatetruecolor($nw, $nh);
    imagecopyresampled($out, $in, 0, 0, 0, 0, $nw, $nh, $w, $h);

    $ok = imagejpeg($out, $dest, $quality);
    imagedestroy($in);
    imagedestroy($out);
    return $ok;
}

Create a smaller JPEG with the GD extension. Resizing also removes hidden data in the original and saves bandwidth.

// .htaccess:  RewriteEngine On
//             RewriteCond %{REQUEST_FILENAME} !-f
//             RewriteRule ^ index.php [L]

$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];

$routes = [
    'GET /'            => fn() => print('Home'),
    'GET /about'       => fn() => print('About'),
    'POST /contact'    => fn() => print('Form received'),
];

$handler = $routes["$method $path"] ?? null;
if (!$handler) { http_response_code(404); exit('Page not found'); }
$handler();

Send every request to index.php and pick the page from the URL path. Pair it with an .htaccess rewrite rule.

try {
    $pdo->beginTransaction();

    $pdo->prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?')->execute([$amount, $from]);
    $pdo->prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?')->execute([$amount, $to]);

    $pdo->commit();
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();   // undo everything
    throw $e;
}

When several queries must all work or all fail (for example moving money between two accounts), wrap them in a transaction. Tables must use InnoDB.

PHP · Slow down password guessingAdvanced
function too_many_attempts(PDO $pdo, string $ident, string $ip, int $max = 5, int $minutes = 15): bool
{
    $st = $pdo->prepare('SELECT COUNT(*) FROM login_attempts
                         WHERE (ident = ? OR ip = ?) AND created_at > (NOW() - INTERVAL ? MINUTE)');
    $st->execute([$ident, $ip, $minutes]);
    return (int)$st->fetchColumn() >= $max;
}

function log_failed_attempt(PDO $pdo, string $ident, string $ip): void
{
    $pdo->prepare('INSERT INTO login_attempts (ident, ip, created_at) VALUES (?, ?, NOW())')->execute([$ident, $ip]);
}

// In the login script
if (too_many_attempts($pdo, $email, $_SERVER['REMOTE_ADDR'])) {
    http_response_code(429);
    exit('Too many attempts. Try again in 15 minutes.');
}
// ... check the password; on failure: log_failed_attempt($pdo, $email, $_SERVER['REMOTE_ADDR']);

Count failed logins per account and per IP in a table and refuse further tries for a while. Needs a table login_attempts(id, ident, ip, created_at).

PHP · Verify a webhook signatureAdvanced
function verifyWebhook(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
    // header looks like:  t=1730000000,v1=5257a869e7...
    $parts = [];
    foreach (explode(',', $header) as $piece) {
        [$k, $v] = array_pad(explode('=', $piece, 2), 2, '');
        $parts[trim($k)] = trim($v);
    }
    if (!isset($parts['t'], $parts['v1']) || abs(time() - (int)$parts['t']) > $tolerance) {
        return false;                                     // missing or too old (replay)
    }
    $expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
    return hash_equals($expected, $parts['v1']);
}

// In your webhook endpoint:
// $raw = file_get_contents('php://input');          // use the raw body, not json_decode()
// if (!verifyWebhook($raw, $_SERVER['HTTP_X_SIGNATURE'] ?? '', 'whsec_from_provider')) {
//     http_response_code(400);
//     exit;
// }

Check that the call really came from the provider: matching signature and a fresh timestamp.

function ipInCidr(string $ip, string $cidr): bool
{
    [$net, $bits] = array_pad(explode('/', $cidr, 2), 2, null);
    $a = @inet_pton($ip);
    $b = @inet_pton((string)$net);
    if ($a === false || $b === false || strlen($a) !== strlen($b)) {
        return false;                                 // invalid or IPv4 vs IPv6 mismatch
    }
    $bits = $bits === null ? strlen($a) * 8 : (int)$bits;
    $bytes = intdiv($bits, 8);
    if ($bytes && substr($a, 0, $bytes) !== substr($b, 0, $bytes)) {
        return false;
    }
    $rest = $bits % 8;
    if ($rest === 0) {
        return true;
    }
    $mask = (0xFF << (8 - $rest)) & 0xFF;
    return (ord($a[$bytes]) & $mask) === (ord($b[$bytes]) & $mask);
}

$allowed = ['203.0.113.0/24', '2001:db8::/32', '198.51.100.7'];
$ok = array_filter($allowed, fn($c) => ipInCidr($_SERVER['REMOTE_ADDR'] ?? '', $c)) !== [];

Works for IPv4 and IPv6. Useful for an admin IP allow-list such as 203.0.113.0/24.

function batchInsert(PDO $pdo, array $rows, int $chunk = 500): int
{
    $total = 0;
    $pdo->beginTransaction();
    try {
        foreach (array_chunk($rows, $chunk) as $part) {
            $marks = implode(',', array_fill(0, count($part), '(?, ?)'));
            $st = $pdo->prepare("INSERT INTO users (name, email) VALUES $marks");
            $st->execute(array_merge(...array_map('array_values', $part)));
            $total += $st->rowCount();
        }
        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }
    return $total;
}

$rows = [];
for ($i = 1; $i <= 1200; $i++) {
    $rows[] = ['name' => "User $i", 'email' => "user$i@example.com"];
}
echo batchInsert($pdo, $rows);          // 1200

One INSERT with many value groups is far faster than one query per row. A transaction keeps it all-or-nothing.

PHP · A small rule-based validatorAdvanced
final class Validator
{
    public array $errors = [];

    public function check(array $data, array $rules): bool
    {
        $this->errors = [];
        foreach ($rules as $field => $ruleString) {
            $value = trim((string)($data[$field] ?? ''));
            foreach (explode('|', $ruleString) as $rule) {
                [$name, $arg] = array_pad(explode(':', $rule, 2), 2, null);
                $bad = match ($name) {
                    'required' => $value === '',
                    'email'    => $value !== '' && !filter_var($value, FILTER_VALIDATE_EMAIL),
                    'min'      => $value !== '' && mb_strlen($value) < (int)$arg,
                    'max'      => mb_strlen($value) > (int)$arg,
                    'int'      => $value !== '' && filter_var($value, FILTER_VALIDATE_INT) === false,
                    default    => false,
                };
                if ($bad) {
                    $this->errors[$field] = "$field failed: $name";
                    break;                                  // one message per field
                }
            }
        }
        return !$this->errors;
    }
}

$v = new Validator();
$ok = $v->check($_POST, ['name' => 'required|min:3|max:50', 'email' => 'required|email', 'age' => 'int']);

Describe the rules as a string per field, get back a list of errors. Easy to read and to extend.

function nextNumber(string $file): int
{
    $fh = fopen($file, 'c+');
    if (!$fh) {
        throw new RuntimeException('Cannot open counter file');
    }
    try {
        flock($fh, LOCK_EX);
        $n = (int)stream_get_contents($fh) + 1;
        ftruncate($fh, 0);
        rewind($fh);
        fwrite($fh, (string)$n);
        fflush($fh);
        flock($fh, LOCK_UN);
        return $n;
    } finally {
        fclose($fh);
    }
}

$invoice = 'INV-' . str_pad((string)nextNumber(__DIR__ . '/invoice.counter'), 6, '0', STR_PAD_LEFT);

Without a lock, two requests can read the same number and both write the same result. flock makes them take turns.

PHP · Memoize a functionAdvanced
function memoize(callable $fn): callable
{
    $cache = [];
    return function (...$args) use ($fn, &$cache) {
        $key = serialize($args);
        if (!array_key_exists($key, $cache)) {
            $cache[$key] = $fn(...$args);
        }
        return $cache[$key];
    };
}

$calls = 0;
$slowSquare = function (int $n) use (&$calls) {
    $calls++;
    return $n * $n;
};

$fast = memoize($slowSquare);
echo $fast(12), $fast(12), $fast(5);     // 144 144 25   ($calls is 2)

Remember results by argument so an expensive call runs only once per input.

function runAll(array $tasks): array
{
    $fibers = array_map(fn(callable $t) => new Fiber($t), $tasks);
    $results = [];

    foreach ($fibers as $f) {
        $f->start();
    }
    while ($fibers) {
        foreach ($fibers as $i => $f) {
            if ($f->isTerminated()) {
                $results[$i] = $f->getReturn();
                unset($fibers[$i]);
            } else {
                $f->resume();
            }
        }
    }
    ksort($results);
    return $results;
}

$log = [];
$job = function (string $name, int $steps) use (&$log) {
    return function () use ($name, $steps, &$log) {
        for ($i = 1; $i <= $steps; $i++) {
            $log[] = "$name$i";
            Fiber::suspend();                       // give others a turn
        }
        return "$name done";
    };
};

$out = runAll([$job('A', 2), $job('B', 3)]);
echo implode(' ', $log);                            // A1 B1 A2 B2 B3

A Fiber can pause itself and be resumed later. This tiny scheduler lets several jobs share one process (PHP 8.1+).

final class Money
{
    public function __construct(
        public readonly int $cents,
        public readonly string $currency = 'PKR',
    ) {
        if ($cents < 0) {
            throw new InvalidArgumentException('Amount cannot be negative');
        }
    }

    public function add(Money $o): static
    {
        if ($o->currency !== $this->currency) {
            throw new InvalidArgumentException('Different currencies');
        }
        return new static($this->cents + $o->cents, $this->currency);
    }

    public function format(): string
    {
        return number_format($this->cents / 100, 2) . ' ' . $this->currency;
    }
}

$total = (new Money(1050))->add(new Money(250));
echo $total->format();                 // 13.00 PKR
// $total->cents = 5;                  // Error: cannot modify readonly property

A readonly property can be set once. Changes create a new object, so nothing is altered by accident.

#[Attribute(Attribute::TARGET_METHOD)]
final class Route
{
    public function __construct(public string $path, public string $method = 'GET') {}
}

final class PageController
{
    #[Route('/hello')]
    public function hello(): string { return 'Hello'; }

    #[Route('/save', 'POST')]
    public function save(): string { return 'Saved'; }
}

function collectRoutes(string $class): array
{
    $routes = [];
    foreach ((new ReflectionClass($class))->getMethods() as $m) {
        foreach ($m->getAttributes(Route::class) as $attr) {
            $r = $attr->newInstance();
            $routes[$r->method . ' ' . $r->path] = [$class, $m->getName()];
        }
    }
    return $routes;
}

$routes = collectRoutes(PageController::class);
[$cls, $method] = $routes['GET /hello'];
echo (new $cls())->$method();

Mark controller methods with #[Route] and let reflection build the route table for you.

function retry(callable $fn, int $times = 4, int $baseMs = 200): mixed
{
    $attempt = 0;
    while (true) {
        try {
            return $fn($attempt);
        } catch (Throwable $e) {
            if (++$attempt >= $times) {
                throw $e;                                       // give up: pass the last error on
            }
            $wait = $baseMs * (2 ** ($attempt - 1));            // 200, 400, 800 ...
            $wait += random_int(0, (int)($wait / 4));           // jitter
            usleep($wait * 1000);
        }
    }
}

// $data = retry(function (int $try) {
//     $raw = @file_get_contents('https://api.example.com/data');
//     if ($raw === false) {
//         throw new RuntimeException('API unreachable');
//     }
//     return json_decode($raw, true);
// });

Network calls fail sometimes. Try again a few times, waiting a little longer each time.

PHP · Stream a large CSV downloadAdvanced
function csvSafe(mixed $v): mixed
{
    if (is_string($v) && $v !== '' && strpbrk($v[0], "=+-@\t\r") !== false) {
        return "'" . $v;                       // stops spreadsheet formula injection
    }
    return $v;
}

function streamCsv(string $filename, array $header, iterable $rows): void
{
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
    $out = fopen('php://output', 'w');
    fwrite($out, "\xEF\xBB\xBF");              // BOM so Excel reads UTF-8
    fputcsv($out, $header);
    foreach ($rows as $row) {
        fputcsv($out, array_map('csvSafe', $row));
    }
    fclose($out);
}

function rows(PDO $pdo): Generator
{
    $st = $pdo->query('SELECT id, name, email FROM users');
    while ($r = $st->fetch(PDO::FETCH_NUM)) {
        yield $r;
    }
}
// streamCsv('users.csv', ['id', 'name', 'email'], rows($pdo));

Write rows straight to the browser one by one. Memory stays small for millions of rows. Cells starting with = + - @ are neutralised.

function uuid4(): string
{
    $b = random_bytes(16);
    $b[6] = chr((ord($b[6]) & 0x0f) | 0x40);        // version 4
    $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);        // variant
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}

function uuid7(): string
{
    $ms = (int)(microtime(true) * 1000);
    $b  = substr(pack('J', $ms), 2) . random_bytes(10);   // 48-bit time + random
    $b[6] = chr((ord($b[6]) & 0x0f) | 0x70);              // version 7
    $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}

echo uuid4(), "\n", uuid7();

v4 is random. v7 starts with the time, so new ids sort in order and are friendlier to database indexes.

function base32Decode(string $s): string
{
    $map = array_flip(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'));
    $bits = '';
    foreach (str_split(strtoupper(rtrim($s, '='))) as $ch) {
        $bits .= str_pad(decbin($map[$ch] ?? 0), 5, '0', STR_PAD_LEFT);
    }
    $out = '';
    foreach (str_split($bits, 8) as $byte) {
        if (strlen($byte) === 8) $out .= chr(bindec($byte));
    }
    return $out;
}

function totp(string $secret, ?int $time = null, int $digits = 6, int $period = 30): string
{
    $counter = intdiv($time ?? time(), $period);
    $hash = hash_hmac('sha1', pack('J', $counter), base32Decode($secret), true);
    $o = ord($hash[19]) & 0x0f;
    $n = ((ord($hash[$o]) & 0x7f) << 24) | (ord($hash[$o + 1]) << 16) | (ord($hash[$o + 2]) << 8) | ord($hash[$o + 3]);
    return str_pad((string)($n % (10 ** $digits)), $digits, '0', STR_PAD_LEFT);
}

function totpVerify(string $secret, string $code, int $drift = 1): bool
{
    for ($i = -$drift; $i <= $drift; $i++) {
        if (hash_equals(totp($secret, time() + $i * 30), $code)) return true;
    }
    return false;
}

The same maths as Google Authenticator (RFC 6238). Allow one step either side for clock drift.

function checkLogin(string $input, string $storedHash, callable $saveHash): bool
{
    if (!password_verify($input, $storedHash)) {
        return false;
    }
    $options = ['memory_cost' => 65536, 'time_cost' => 4, 'threads' => 1];
    if (password_needs_rehash($storedHash, PASSWORD_ARGON2ID, $options)) {
        $saveHash(password_hash($input, PASSWORD_ARGON2ID, $options));   // store the stronger hash
    }
    return true;
}

// usage: checkLogin($_POST['password'], $user['password_hash'], fn($h) => updateUserHash($user['id'], $h));

When you raise the cost or change the algorithm, upgrade each hash the next time that user logs in.

function allow(string $key, int $max, int $windowSeconds): bool
{
    $file = sys_get_temp_dir() . '/rl_' . hash('sha256', $key);
    $fh = fopen($file, 'c+');
    if (!$fh) {
        return true;                              // fail open if the disk is unavailable
    }
    flock($fh, LOCK_EX);
    $data = json_decode((string)stream_get_contents($fh), true) ?: ['start' => time(), 'n' => 0];

    if (time() - $data['start'] >= $windowSeconds) {
        $data = ['start' => time(), 'n' => 0];
    }
    $data['n']++;

    ftruncate($fh, 0);
    rewind($fh);
    fwrite($fh, json_encode($data));
    flock($fh, LOCK_UN);
    fclose($fh);

    return $data['n'] <= $max;
}

if (!allow($_SERVER['REMOTE_ADDR'] ?? 'cli', 60, 60)) {
    http_response_code(429);
    exit('Too many requests');
}

Allow N requests per window for each key (for example an IP). flock keeps the counter correct under load.

$nonce = base64_encode(random_bytes(16));

header("Content-Security-Policy: default-src 'self'; "
     . "script-src 'self' 'nonce-$nonce'; "
     . "style-src 'self'; img-src 'self' data:; "
     . "object-src 'none'; base-uri 'none'; frame-ancestors 'none'");

// In the page:
echo '<script nonce="' . htmlspecialchars($nonce, ENT_QUOTES) . '">console.log("allowed");</script>';

A nonce lets only your own inline script run. Make a new one on every request.

function b64u(string $s): string { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); }
function b64d(string $s): string { return (string)base64_decode(strtr($s, '-_', '+/')); }

function jwtSign(array $claims, string $secret, int $ttl = 3600): string
{
    $head = b64u(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
    $body = b64u(json_encode($claims + ['iat' => time(), 'exp' => time() + $ttl]));
    $sig  = b64u(hash_hmac('sha256', "$head.$body", $secret, true));
    return "$head.$body.$sig";
}

function jwtVerify(string $jwt, string $secret): ?array
{
    $parts = explode('.', $jwt);
    if (count($parts) !== 3) return null;
    [$head, $body, $sig] = $parts;
    $h = json_decode(b64d($head), true);
    if (($h['alg'] ?? '') !== 'HS256') return null;                 // never trust the token's own alg choice
    $good = b64u(hash_hmac('sha256', "$head.$body", $secret, true));
    if (!hash_equals($good, $sig)) return null;
    $claims = json_decode(b64d($body), true);
    return is_array($claims) && ($claims['exp'] ?? 0) >= time() ? $claims : null;
}

$jwt = jwtSign(['sub' => 42, 'role' => 'editor'], 'server-secret');
print_r(jwtVerify($jwt, 'server-secret'));

A JWT is three base64url parts: header, payload, signature. Always check the signature and the expiry.

function encryptText(string $plain, string $key): string
{
    $nonce  = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipher = sodium_crypto_secretbox($plain, $nonce, $key);
    return base64_encode($nonce . $cipher);
}

function decryptText(string $packed, string $key): ?string
{
    $raw = base64_decode($packed, true);
    if ($raw === false || strlen($raw) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES) {
        return null;
    }
    $nonce  = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipher = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $plain  = sodium_crypto_secretbox_open($cipher, $nonce, $key);
    return $plain === false ? null : $plain;
}

$key   = sodium_crypto_secretbox_keygen();      // 32 bytes: generate once, store safely
$token = encryptText('card note: 1234', $key);
echo decryptText($token, $key);                 // card note: 1234

Authenticated encryption in a few lines. The key is kept in config, never in the database.

PHP · Signed, expiring linksAdvanced
function signUrl(string $path, int $ttl, string $secret): string
{
    $expires = time() + $ttl;
    $sig = hash_hmac('sha256', $path . '|' . $expires, $secret);
    return $path . '?expires=' . $expires . '&sig=' . $sig;
}

function verifyUrl(string $path, int $expires, string $sig, string $secret): bool
{
    if ($expires < time()) {
        return false;                                    // expired
    }
    $good = hash_hmac('sha256', $path . '|' . $expires, $secret);
    return hash_equals($good, $sig);                     // constant-time compare
}

$secret = 'long-random-secret-from-config';
$url = signUrl('/download/report.pdf', 600, $secret);
parse_str((string)parse_url($url, PHP_URL_QUERY), $q);
var_dump(verifyUrl('/download/report.pdf', (int)$q['expires'], $q['sig'], $secret));   // true

A signature proves the link was made by you and was not changed. Good for download or invite links.

PHP · A file cache with expiryAdvanced
function cache(string $key, int $ttl, callable $build): mixed
{
    $file = sys_get_temp_dir() . '/cache_' . hash('sha256', $key) . '.php';

    if (is_file($file) && filemtime($file) > time() - $ttl) {
        $data = @unserialize((string)file_get_contents($file));
        if (is_array($data) && array_key_exists('v', $data)) {
            return $data['v'];
        }
    }

    $value = $build();
    $tmp = $file . '.' . bin2hex(random_bytes(4));
    file_put_contents($tmp, serialize(['v' => $value]), LOCK_EX);
    rename($tmp, $file);                       // atomic replace
    return $value;
}

$rates = cache('usd-rates', 600, function () {
    return ['PKR' => 280.5];                   // slow API call goes here
});

Cache slow results (an API call, a heavy query) in a file. The temp-then-rename write avoids half-written files.

$sql = 'INSERT INTO users (name, email, hits) VALUES (:name, :email, 1)
        ON DUPLICATE KEY UPDATE name = VALUES(name), hits = hits + 1';

$st = $pdo->prepare($sql);
$st->execute([':name' => 'Ali', ':email' => 'ali@x.com']);     // existing email: updates
$st->execute([':name' => 'New', ':email' => 'new@x.com']);     // new email: inserts

// rowCount(): 1 = inserted, 2 = updated, 0 = nothing changed

ON DUPLICATE KEY UPDATE inserts a new row or updates the existing one. Needs a UNIQUE key.

function buildWhere(array $filters, array $allowed): array
{
    $parts = [];
    $params = [];
    foreach ($filters as $col => $value) {
        if (!isset($allowed[$col]) || $value === '' || $value === null) {
            continue;                                   // unknown or empty: ignore
        }
        $type = $allowed[$col];                         // 'eq' | 'like' | 'min' | 'max'
        $name = ':f_' . count($params);
        $parts[] = match ($type) {
            'like' => "`$col` LIKE $name",
            'min'  => "`$col` >= $name",
            'max'  => "`$col` <= $name",
            default => "`$col` = $name",
        };
        $params[$name] = $type === 'like' ? '%' . addcslashes((string)$value, '\\%_') . '%' : $value;
    }
    return [$parts ? 'WHERE ' . implode(' AND ', $parts) : '', $params];
}

[$where, $params] = buildWhere($_GET, ['name' => 'like', 'active' => 'eq', 'hits' => 'min']);
$st = $pdo->prepare("SELECT id, name FROM users $where ORDER BY id");
$st->execute($params);
$rows = $st->fetchAll();

Only column names from your own allow-list reach the SQL. Values always travel as parameters.

PHP · Repository pattern with PDOAdvanced
final class UserRepository
{
    public function __construct(private PDO $pdo) {}

    public function find(int $id): ?array
    {
        $st = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
        $st->execute([$id]);
        return $st->fetch() ?: null;
    }

    public function findByEmail(string $email): ?array
    {
        $st = $this->pdo->prepare('SELECT * FROM users WHERE email = ?');
        $st->execute([$email]);
        return $st->fetch() ?: null;
    }

    public function save(array $u): int
    {
        if (!empty($u['id'])) {
            $st = $this->pdo->prepare('UPDATE users SET name = ?, email = ? WHERE id = ?');
            $st->execute([$u['name'], $u['email'], $u['id']]);
            return (int)$u['id'];
        }
        $st = $this->pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
        $st->execute([$u['name'], $u['email']]);
        return (int)$this->pdo->lastInsertId();
    }
}

$users = new UserRepository($pdo);
$id = $users->save(['name' => 'Hina', 'email' => 'hina@example.com']);
$users->save(['id' => $id, 'name' => 'Hina Q', 'email' => 'hina@example.com']);
$u = $users->find($id);

Keep SQL in one class. The rest of the app asks for users and never writes queries.

PHP · A small event dispatcherAdvanced
final class Events
{
    private array $listeners = [];

    public function on(string $event, callable $listener, int $priority = 0): void
    {
        $this->listeners[$event][$priority][] = $listener;
    }

    public function emit(string $event, array $payload = []): void
    {
        $byPriority = $this->listeners[$event] ?? [];
        krsort($byPriority);                         // higher priority first
        foreach ($byPriority as $listeners) {
            foreach ($listeners as $listener) {
                if ($listener($payload) === false) {
                    return;                          // a listener can stop the chain
                }
            }
        }
    }
}

$events = new Events();
$events->on('user.registered', fn($p) => print("Welcome mail to {$p['email']}\n"));
$events->on('user.registered', fn($p) => print("Audit log first\n"), 10);
$events->emit('user.registered', ['email' => 'ali@example.com']);

Let one part of the code announce something happened and others react, without knowing each other.

PHP · A middleware pipelineAdvanced
function pipeline(array $middleware, callable $core): callable
{
    $next = $core;
    foreach (array_reverse($middleware) as $mw) {
        $next = fn(array $req) => $mw($req, $next);
    }
    return $next;
}

$auth = function (array $req, callable $next) {
    if (empty($req['user'])) {
        return ['status' => 401, 'body' => 'Login required'];
    }
    return $next($req);
};
$timer = function (array $req, callable $next) {
    $res = $next($req);
    $res['headers']['X-Time'] = 'ok';
    return $res;
};

$app = pipeline([$timer, $auth], fn(array $req) => ['status' => 200, 'body' => 'Hello ' . $req['user']]);

print_r($app(['user' => 'Ali']));
print_r($app([]));

Each middleware can act before and after the next one. The last step is your real handler.

PHP · A tiny dependency containerAdvanced
final class Container
{
    private array $factories = [];
    private array $instances = [];

    public function set(string $id, callable $factory): void
    {
        $this->factories[$id] = $factory;
        unset($this->instances[$id]);
    }

    public function get(string $id): mixed
    {
        if (!array_key_exists($id, $this->instances)) {
            if (!isset($this->factories[$id])) {
                throw new RuntimeException("Nothing registered for '$id'");
            }
            $this->instances[$id] = ($this->factories[$id])($this);
        }
        return $this->instances[$id];
    }
}

$c = new Container();
$c->set('config', fn() => ['dsn' => 'mysql:host=localhost;dbname=app']);
$c->set('pdo', fn(Container $c) => new PDO($c->get('config')['dsn'], 'root', ''));
// $pdo = $c->get('pdo');   // same object every time

Register how to build things once, then ask for them anywhere. Each service is created only when first used.