-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
142: Practice Exercise: Building a Simple ORM from Scratch
You've probably spent the last few lessons writing a lot of repetitive SQL. You create a User class, then you write a UserRepository, and inside that repository, you manually map database columns to object properties. It feels fine when you only have one or two tables, but the moment your application grows to twenty tables, you'll realize you're just writing the same INSERT and UPDATE logic over and over again with slightly different column names. That's the exact frustration that leads to the creation of an ORM (Object-Relational Mapper).
The manual mapping grind
When I first started building apps, my "ORM" was basically just a series of associative arrays that I cast into objects. I'd write something like this to fetch a product from an e-commerce database:
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$product = new Product();
$product->id = $row['id'];
$product->name = $row['name'];
$product->price = $row['price'];
$product->description = $row['description'];
// ... and so on for every single column
This is what I call the "naive" way. It's explicit, which is nice, but it's a maintenance nightmare. If you add a discount_price column to your database, you have to hunt down every single place where you manually mapped that result set and add a new line of code. You're essentially duplicating your database schema in your PHP code, and doing so manually. It's boring work, and boring work is where bugs live.
Moving toward a generic Data Mapper
The better way—the way that actually scales—is to realize that almost every table follows the same CRUD pattern. Whether it's a Product, a User, or an Order, you're usually just doing a SELECT * or an UPDATE table SET col = val. I prefer to build a base Model class that handles the heavy lifting using a bit of PHP magic.
Instead of writing a repository for every entity, we can create a base class that knows how to inspect itself. By using the class name as the table name and the object's public properties as the columns, we can automate the mapping. Here is the conceptual shift:
abstract class Model {
protected static $pdo;
public static function setDb($pdo) {
self::$pdo = $pdo;
}
public static function find($id) {
$table = strtolower(get_called_class()); // e.g., "Product" -> "product"
$stmt = self::$pdo->prepare("SELECT * FROM $table WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$data) return null;
$instance = new static();
foreach ($data as $key => $value) {
$instance->$key = $value;
}
return $instance;
}
public function save() {
$table = strtolower(get_called_class());
$properties = get_object_vars($this);
$columns = array_keys($properties);
$values = array_values($properties);
$setClause = implode(' = ?, ', $columns) . ' = ?';
$sql = "UPDATE $table SET $setClause WHERE id = {$this->id}";
return self::$pdo->prepare($sql)->execute($values);
}
}
The cost of abstraction
Now, I should be honest with you: this isn't a free lunch. By moving to this generic approach, you're trading a tiny bit of performance for a massive gain in developer velocity. Calling get_object_vars() and looping through arrays is technically slower than writing $product->name = $row['name']. In a high-traffic environment, that overhead can add up. However, for 95% of applications, the bottleneck is the network trip to the database, not the few microseconds PHP spends mapping a row to an object.
The real risk here is "magic." When you use a base model, it's not immediately obvious to a new developer where the SQL is actually happening. You've hidden the database logic inside a parent class. To mitigate this, I always keep my base models slim. If I need a complex query—like a report that joins five different tables—I don't try to force it into the ORM. I just write a dedicated method for that specific query. Don't let the desire for a "perfect" system stop you from writing a raw SQL query when it's clearly the better tool for the job.
📋 Practical Task
Exercise: Implementing a Dynamic CRUD Base Model for a User Directory
Your goal is to build a minimal ORM system that allows you to manage users in a database without writing repetitive SQL for every property.
Requirements:
- Create a database table named
userswith columns:id(INT, PK),username(VARCHAR),email(VARCHAR), andbio(TEXT). - Create an abstract class
BaseModelthat contains:- A static
$dbproperty to hold the PDO connection. - A static
find($id)method that usesget_called_class()to determine the table name and returns an instance of the child class populated with database data. - A
save()method that dynamically generates anUPDATEstatement based on the object's current properties.
- A static
- Create a
Userclass that extendsBaseModel. It should have public properties matching the database columns. - Write a script that:
- Connects to the database via PDO.
- Sets the PDO connection in
BaseModel. - Fetches a user by ID using
User::find($id). - Changes the user's
bioproperty. - Calls
$user->save()to persist the change to the database.
There are no comments for now.