Models

Chapter 4

Introduction


A model represents a set of data. Normally the set of data is table in a database but it could also be a directory in a file system or an XML file.

Creating a New Model (activeRecord)


To add a new model to your application first create a new table in your database. Make sure the name of the table is in pluralized form. For example if I want a table that stores articles make sure to call it "articles".

Now you'll need to make Madeam aware of this new table in the database. To do so just create a new file in your models directory. This file will contain the model's class. Name the file after the table in the database but in singalized form. For example our articles table would have a model file called "article_model.php"

Now create the model's class in the file like so:

<?php
# models/article_model.php
class articleModel extends activeRecord {

}
?>

Tada! You've just added a new model to your application.

Relationships


Madeam's active record class handles relationships between data structures (typically tables in a database but they could be other things). For example you can create a relationship between Articles and Comments by doing the following:

<?php
# models/article_model.php
class articleModel extends activeRecord {
  var $has_many_comments;
}
?>

<?php
# models/comment_model.php
class commentModel extends activeRecord {
  var $belongs_to_article;
}
?>

What we just did was say that a single article entry has many comments and a single comment entry has one article. Remember that models represent a single row.

Entry Validation


Before data is saved to the database it is passed through validators. You can define your own validators or use the existing ones that come with Madeam. To use a validator for a field type the following at the top of your mode's class:

<?php
var $validate_title_isnotempty = array('message' =>'Please fill in a title.');
?>

Where "title" is the name of the field in the database and "isnotempty" is the name of the method that is called by madeam and that validates the value of the title. In this case to make sure it's not empty.

Built-in Validators

  • [name] - [description] - [variables]
  • isnotempty - Makes sure the value of the field is not empty
  • isemail - Verifies that the format of the value is an email
  • isexpression - Verifies that the value matches a regular expression - (regexp)
  • islength - Checks that the string's length isn't too long or too short - (min, max)
  • isnotequal - Make sure that the field doesn't have a certain value - (value)

Update vs Insert validation

When inserting a record for the first time all fields are validated. When updating a record only fields that exist in your entry array will be validated.

This is because we assume that the values already in the database have already passed validation.

NOTE: For validation error messages to work you must have sessions enabled. You can do so by adding "session_start();" to your before_action() callback in you application controller.

Callbacks


All models have callbacks which can be defined in their class or in the application model file (models/_app_model.php)

before_validation()

When defined the code inside of this method executes before any validation is done. Validation of data is done whenever someone attempts to update or add a new entry to the database. This is also useful place to dynamically add your own validators. For example:

<?php
$this->validator([field_name], [method_name], [arguments array]);
?>

after_validation()

All code within this method executes after the data has been validated.

before_save()

Before data is saved to the database and it has passed validation this callback is called. This callback will not be called if the data fails to pass validation. This is a useful place to format your data before it's saved like formating dates or encoding passwords.

after_save()

This callback is called after the data has been saved to the database.

before_delete()

Called before something is deleted.

after_delete()

Called after something is deleted.

before_find()

When someone uses a method like find_all() or find_one() this callback is called before the query is executed. This is a useful place to modify the query before it's executed for example by adding new where clauses.

after_find()

After someone uses one of the find methods this callback is called. This is a useful place to alter the format in which the data is returned and to add more data or format the actual data.

Query Methods


Query methods allow you to alter and perform queries within the model's context. You can also chain some query methods together like so:

<?php
$this->Article->where("category = 32")->order("id DESC")->limit(25)->find_all();
?>

You can also modify the query of related models. For example let's say we want to get an article but only 20 of it's related comments.
<?php
// limit the number of comments returned for this article
$this->Article->Comment->limit(20);

// find the article
$this->Article->find_one(32);
?>

find_one(id)

Find a single entry by it's primary key.

<?php
$this->Article->find_one(32);
?>

find_all()

Find all the records in the database that match the query.

<?php
$this->Article->find_all();
?>

find_list(label, value)

Return many records in the format of a list. Very useful for generating drop down menus.

<?php
$this->Article->find_list('title', 'id');
?>

find_one_by_[field](value)

Find a single entry by a specific field instead of the primary key.

<?php
$this->Article->find_one_by_slug('some-title');
?>

find_all_by_[field](value)

Find all the records who's specified field matches the value given.

<?php
$this->Article->find_all_by_category(32);
?>

save()

INSERT or UPDATE a single record in the database. Madeam will INSERT a new row if a value for the primary key is null or non-existent otherwise Madeam will UPDATE an existing row.

<?php
$this->Article->save(array('title' => 'New Title', 'body' => 'Cool article'));
?>

delete(id)

Delete a single row in the database.

<?php
$this->Article->delete(32);
?>

habtm_add(model, id, associate_id(s))

Add one or more relationships between 2 models that are related by has_and_belongs_to_many.

<?php
// relate a single article to a single tag
$this->Article->habtm_add('Tag', 32, 25);

// relate a single article to multiple tags
$this->Article->habtm_add('Tag', 32, array(23, 45));
?>

habtm_delete(model, id, associate_id(s))

Remove one or more relationships between 2 models that are related by has_and_belongs_to_many.

<?php
// removes a single tag from an article
$this->Article->habtm_delete('Tag', 32, 25);

// removes multiple tags from an article
$this->Article->habtm_delete('Tag', 32, array(23, 45));
?>

describe()

DESCRIBEs the model's table

<?php
$this->Article->describe();
?>

where(condition)

Set a WHERE condition for the query. Every new WHERE condition added is joined by an "AND" operator.

<?php
// WHERE id = 32
$this->Article->where("id = 32");

// WHERE category = 45 OR category = 32 AND title LIKE '%$search%'
$this->Article->where("category = 45 OR category = 32");
$this->Article->where("title LIKE '%$search%'");
?>

order()

Set the ORDER of a query.

<?php
$this->Article->order("id DESC");
?>

join(model, on)

JOIN models together.

<?php
// joins the Comment model based on foreign key naming conventions
$this->Article->join('Comment');

// joins the Comment model with a custom ON condition
$this->Article->join('Comment', "comments.article = articles.id");
?>

in(field, values)

<?php
// gets all the articles who's ID is either 32, 45, 66 or 99
$this->Article->in('id', array(32, 45, 66, 99));
?>

limit(start, offset)

Limit the number of records returned. You can also specify a starting point.

<?php
// LIMIT 0, 10
$this->Article->limit(10);

// LIMIT 5, 10
$this->Article->limit(5, 10);
?>

fields()

Specify which fields you wish to call from the database.

<?php
$this->Article->fields('title', 'id', 'body');
?>

unbind(model)

Unbind a model that is related.

<?php
$this->Article->unbind('Comment', 'Tag', 'Category');
?>

unbind_all()

Unbind all the related models. You can also exclude models as show below.
<?php
// Unbinds all related models
$this->Article->unbind_all();

// Unbinds all related models except for the Comment model
$this->Article->unbind_all('Comment');
?>
Previous Chapter Next Chapter