Skip to Content
Course content

177: Building a Simple CMS with Custom Fields

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

Let's say we're building a movie database CMS. Initially, it's simple: every movie has a title, a release date, and a plot summary. You've got your movies table, and everything is humming along. But then, the client comes back and says, "I want to track the Director for some movies, the Budget for others, and maybe a 'Rotten Tomatoes Score' for a few."

The temptation of the wide table

When I first started doing this, my instinct was always to just add more columns. It feels intuitive. You run an ALTER TABLE movies ADD COLUMN director VARCHAR(255), and suddenly you have a place for that data. It's fast to implement, and querying it is a breeze because it's just another column in your SELECT * statement.

// The naive way: Hardcoded columns
$sql = "SELECT title, director, budget, rotten_tomatoes_score FROM movies WHERE id = ?";
$movie = $db->query($sql, [$id])->fetch();

echo "Director: " . $movie['director'];

The problem is that this approach doesn't scale—not in terms of performance, but in terms of sanity. Once you have fifty different "custom" fields, your table becomes a wasteland of NULL values. Most movies won't have a "Budget" listed; most won't have a "Production Company" column filled. You end up with a massive, sparse table that's a nightmare to maintain. Every time the client wants a new field, you're running migrations on a production database, which is a habit that will eventually get you a very unpleasant phone call at 3 AM.

Trading query simplicity for flexibility

The better way—and the way most professional CMSs like WordPress handle this—is a metadata table. Instead of making the table wider, we make it deeper. We create a separate table, let's call it movie_meta, with three columns: movie_id, meta_key, and meta_value. Now, if a movie needs a "Director" field, you just add a row to the meta table. If it needs a "Budget" field, you add another row. You never have to touch the database schema again.

Now, I'll be honest with you: this makes your SQL slightly more complex. You can't just grab everything in one flat row. You have to join the tables or run a second query to fetch the metadata. But the trade-off is worth it. You've shifted the definition of your data from the structure of the database to the content of the database.

Implementing the meta-fetcher

To make this usable in PHP, you don't want to be looping through a raw result set every time you need a value. I usually write a small helper function that collapses these rows into a clean associative array. This gives you the best of both worlds: the flexibility of a key-value store and the ease of use of a standard PHP array.

// The better way: The metadata pattern
function get_movie_meta($db, $movie_id) {
    $stmt = $db->prepare("SELECT meta_key, meta_value FROM movie_meta WHERE movie_id = ?");
    $stmt->execute([$movie_id]);
    
    // We use array_column or a loop to transform the rows into a key => value pair
    $meta = [];
    while ($row = $stmt->fetch()) {
        $meta[$row['meta_key']] = $row['meta_value'];
    }
    return $meta;
}

$movie_id = 42;
$details = get_movie_meta($db, $movie_id);

// Now it's as easy as the naive way, but infinitely more flexible
echo "Director: " . ($details['director'] ?? 'Unknown');
echo "Budget: " . ($details['budget'] ?? 'N/A');

By doing this, your CMS becomes truly dynamic. You can now build an admin panel where the user can literally type in a new field name and a value, and your code will handle it without you ever having to open a database management tool. You've essentially built a mini-schema inside your data.




📋 Practical Task

Build a Property Listing Attribute System

You are tasked with adding a "Custom Specs" feature to a Real Estate CMS. Instead of adding columns for every possible house feature (like "Pool", "Garage Size", or "Heating Type"), implement the metadata pattern.

  • Create a mock database structure (or use a real one) with a properties table and a property_meta table (containing property_id, meta_key, and meta_value).
  • Write a PHP function getPropertySpecs($db, $property_id) that retrieves all custom fields for a specific house and returns them as an associative array.
  • Create a simple loop that iterates through this array and prints the specs in an HTML list (e.g., <li>Pool: Yes</li>).
  • Test your code by adding three different custom fields to one property in the database and ensuring they all render correctly without hardcoding the field names in your PHP display logic.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.