PHP
Completed
-
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
177: Building a Simple CMS with Custom Fields
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
propertiestable and aproperty_metatable (containingproperty_id,meta_key, andmeta_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.
There are no comments for now.