PHP Class Examples
Production-ready PHP classes demonstrating modern OOP patterns, security best practices, and clean code principles.
User Authentication Class
Secure user authentication with password hashing and session management.
Intermediate
php
1<?php
2declare(strict_types=1);
3
4namespace App\Auth;
5
6class UserAuthenticator
7{
8 private PDO $db;
9
10 public function __construct(PDO $database)
11 {
12 $this->db = $database;
13 }
14
15 public function register(string $email, string $password): bool
16 {
17 $hash = password_hash($password, PASSWORD_ARGON2ID);
18
19 $stmt = $this->db->prepare(
20 "INSERT INTO users (email, password) VALUES (?, ?)"
21 );
22
23 return $stmt->execute([$email, $hash]);
24 }
25
26 public function authenticate(string $email, string $password): bool
27 {
28 $stmt = $this->db->prepare(
29 "SELECT password FROM users WHERE email = ?"
30 );
31 $stmt->execute([$email]);
32 $user = $stmt->fetch();
33
34 return $user && password_verify($password, $user['password']);
35 }
36}Database Query Builder
Fluent interface for building SQL queries safely with prepared statements.
Advanced
php
1<?php
2declare(strict_types=1);
3
4namespace App\Database;
5
6class QueryBuilder
7{
8 private PDO $pdo;
9 private string $table = '';
10 private array $wheres = [];
11 private array $bindings = [];
12
13 public function __construct(PDO $pdo)
14 {
15 $this->pdo = $pdo;
16 }
17
18 public function table(string $table): self
19 {
20 $this->table = $table;
21 return $this;
22 }
23
24 public function where(string $column, string $operator, mixed $value): self
25 {
26 $this->wheres[] = "$column $operator ?";
27 $this->bindings[] = $value;
28 return $this;
29 }
30
31 public function get(): array
32 {
33 $sql = "SELECT * FROM {$this->table}";
34
35 if (!empty($this->wheres)) {
36 $sql .= " WHERE " . implode(' AND ', $this->wheres);
37 }
38
39 $stmt = $this->pdo->prepare($sql);
40 $stmt->execute($this->bindings);
41
42 return $stmt->fetchAll(PDO::FETCH_ASSOC);
43 }
44}Validation Class
Flexible data validation with custom rules and error messages.
Beginner
php
1<?php
2declare(strict_types=1);
3
4namespace App\Validation;
5
6class Validator
7{
8 private array $errors = [];
9
10 public function validate(array $data, array $rules): bool
11 {
12 foreach ($rules as $field => $ruleSet) {
13 $value = $data[$field] ?? null;
14
15 foreach (explode('|', $ruleSet) as $rule) {
16 $this->applyRule($field, $value, $rule);
17 }
18 }
19
20 return empty($this->errors);
21 }
22
23 private function applyRule(string $field, mixed $value, string $rule): void
24 {
25 if ($rule === 'required' && empty($value)) {
26 $this->errors[$field][] = "The $field field is required.";
27 }
28
29 if ($rule === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
30 $this->errors[$field][] = "The $field must be a valid email.";
31 }
32
33 if (str_starts_with($rule, 'min:')) {
34 $min = (int) substr($rule, 4);
35 if (strlen((string)$value) < $min) {
36 $this->errors[$field][] = "The $field must be at least $min characters.";
37 }
38 }
39 }
40
41 public function errors(): array
42 {
43 return $this->errors;
44 }
45}API Response Handler
Standardized JSON API responses with proper HTTP status codes.
Intermediate
php
1<?php
2declare(strict_types=1);
3
4namespace App\Http;
5
6class JsonResponse
7{
8 public static function success(mixed $data, int $status = 200): void
9 {
10 http_response_code($status);
11 header('Content-Type: application/json');
12
13 echo json_encode([
14 'success' => true,
15 'data' => $data,
16 ], JSON_THROW_ON_ERROR);
17
18 exit;
19 }
20
21 public static function error(string $message, int $status = 400): void
22 {
23 http_response_code($status);
24 header('Content-Type: application/json');
25
26 echo json_encode([
27 'success' => false,
28 'error' => $message,
29 ], JSON_THROW_ON_ERROR);
30
31 exit;
32 }
33
34 public static function validationError(array $errors): void
35 {
36 self::error('Validation failed', 422);
37 }
38}Want More Examples?
Explore our comprehensive tutorials to learn how to build these classes step-by-step with detailed explanations.
Browse Tutorials