Constructing Models

A Model is a representation of a database object. It is similiar to a ResultSet object in that it has attributes for each of the data tables columns and it is iterable. But it’s also so much more.

Models can also access referenced data, provide easy methods for loading, saving and inserting data, and provide an easy mechanism for data validation.

But before we can use database models, there are a few rules to follow when constructing our database schemas.

Constructing Schemas: The Rules

The Model class and the underlying CRUD class architecture provide a great deal of automation on the developers behalf. But this only works best when we set the data up in an easy-to-follow manner. It’s very possible that CRUD and Models will work to some extant with the worst of schemas, but to get the best bang for your buck, you’re best to follow these simple rules:

  1. Your database table names should be plural. For example: users, groups, projects, cities, cars, houses, markets, etc.
  2. Each table should have a primary key defined. If the primary key is a single database column, it should be the singular form of the table name, with “_id” prepended. Example: user_id, group_id, project_id, city_id, car_id, house_id, market_id, etc.
  3. Any column that references another table does not have to have the related table as part of it’s name, but the column should end in “_id,” just like primary keys.
  4. All foreign keys/references should be defined in the database schema as such.
  5. Tables can have compound primary keys, but cannot have compound foreign keys/references. If this is required, the table being referenced should have a single column primary key added.

Following these fairly simple rules, you can now being creating your Model classes.

Creating Model Classes

Creating a model is painfully simple. If you have a database table named cars, all you have to do is create a new class for cars that inherits from the Model class.

Note: The name of the class should be the singular name of the database table. This makes sense if you realize that we will only be reading, inserting or updating one record at a time.

<?php
    class Car extends Model
    {
 
    }
?>

That’s it! It’s that simple! You’ve created your first model. But what can you do with it? How about a teaser:

<?php
    // Loading a car record:
 
    $oCar = new Car( 14 );
 
    // Updating a record:
 
    $oCar = new Car( 14 );
    $oCar->make = "Saturn";
    $oCar->color = "Green";
    $oCar->Save();
 
    // Inserting a record:
 
    $oCar = new Car( array(
        "make" => "Saturn",
        "model" => "Vue",
        "year" => "2006",
        "color" => "Orange"
    ) );
 
    $oCar->Save();
 
    // Deleting a record:
 
    $oCar = new Car( 14 );
    $oCar->Destroy();
?>

Looks amazingly simple to manipulate data, doesn’t it?

In the following chapters, we’ll dig deeper into the Model architecture to show more advanced ways to manipulate data.