Skip to Content
Course content

142: Practice Exercise: Building a Simple ORM from Scratch

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 users with columns: id (INT, PK), username (VARCHAR), email (VARCHAR), and bio (TEXT).
  • Create an abstract class BaseModel that contains:
    • A static $db property to hold the PDO connection.
    • A static find($id) method that uses get_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 an UPDATE statement based on the object's current properties.
  • Create a User class that extends BaseModel. It should have public properties matching the database columns.
  • Write a script that:
    1. Connects to the database via PDO.
    2. Sets the PDO connection in BaseModel.
    3. Fetches a user by ID using User::find($id).
    4. Changes the user's bio property.
    5. Calls $user->save() to persist the change to the database.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.