-
Notifications
You must be signed in to change notification settings - Fork 2
Models
Home > Models
Models are used to get, insert, update and remove data from a database. Here is a basic code for one.
<?php
/* Example of basic model setup */
class Blogpost_Model extends Model {
public function __construct() {
$this->setTableName('blog_posts');
$this->addField('id', array(
'key'
));
$this->addField('name');
}
}
?>This is how you set the table name for the database.
<?php
/* set the table name to use in the DB */
$this->setTableName('blog_posts');
?>It is good to set this within the __construct for the model.
This is how you add a field to the database.
<?php
$this->addField('id', array(
'key',
));
?>The first parameter is the name of the column and the second parameter is an array of options. The available options are
<?php
$this->addField('id', array(
/* sets the field as a key. Can have multiple keys for each model */
'key',
/* sets the field as required and must have a value before submitting to the database */
'required',
/* sets a method that can be used to validate the value of the column against before
submitting to the database. You can set multiple validate functions using an array.
You can set an error message using key, value pairs. */
'validate' => 'function name',
'validate' => array('function1', 'function2', ...),
'validate' => array('function1' => 'Error message'),
/* lets you format the value of a column either when setting the variable or getting it.
It defaults to onGet. If you specify only a function then it will assume it is in the current
class if it isn't one of the predefined formatters. You can specify a class and function */
'format' => 'functionName', /* defaults to onGet
'format' => array(
'onGet' => 'functionName',
'onSet' => array('Class_Name', 'functionName'),
),
));
?>It is good to set these within the __construct for the model.
This is how you create a one-to-one relationship.
<?php
$this->hasOne('Client_Model', array(
/* the column within this model to use in the relationship */
'local' => 'user_id',
/* the column within the other model to use in the relationship */
'foreign' => 'id',
/* the alias for the relationship. This is used to pull the data
from the relationship */
'alias' => 'createdBy',
));
?>The first parameter is the class of the model to relate to. The second parameter contains options. All three: local, foreign, and alias are required.
It is good to set this in the __construct for the model.
This is how you create a one-to-many relationship.
<?php
$this->hasMany('Client_Model', array(
/* the column within this model to use in the relationship */
'local' => 'user_id',
/* the column within the other model to use in the relationship */
'foreign' => 'id',
/* the alias for the relationship. This is used to pull the data
from the relationship */
'alias' => 'createdBy',
));
?>The first parameter is the class of the model to relate to. The second parameter contains options. All three: local, foreign, and alias are required.
It is good to set this in the __construct for the model.
Values for columns can be passed into validators to make sure they pass certain requirements before being inserted into the database. The requirements can be anything including checking the length of a string, checking to see if a username already exists, or even checking the complexity of a password.
If a validator fails then it must return either a string which will be used as the error message or false. If false is returned then the message that is set using key, value pairs will be used or a default error message is used if no other message has been set.
Validators have two arguments. The first is the name of the field and the second is the value being checked. Here is an example.
<?php
public function maxlength($field, $value) {
if (strlen($value) > 255) {
return "$field is too long. Can only have up to 255 characters";
}
return true;
}
?>Formatters alter the value of a column to format it in a specific way when getting or setting it. Formatters can be used to typecast or to remove HTML from values. You can define your own formatters or use predefined ones. The predefined formatters are: integer, plaintext, htmltext and timestamp.
Formatters have one argument which is the value of the column. Formatters must return the value after it has been formatted. Here is an example.
<?php
public function formatDate($value) {
return date('m/d/y', $value);
}
?>Retrieving one row from the database using a key
Here is how you retrieve one row from the database using a primary key
<?php
$post = new BlogPost_Model;
$post->retrieve(895);
?>The value of columns can be accessed directly using the name of the column like this
<?php
echo $post->title;
echo $post->time;
?>Relationships get access the same way as columns except using the alias. You can also use the function get().
<?php
echo $post->author->name;
echo $post->get('author')->name;
?>Here is how you do a find
<?php
$post->find(array(
'where' => array('is_active = ? and is_deleted = ?', 'yes', 'no'),
'order' => 'time DESC',
'limit' => 500,
));
?>Question marks within the where statement get replaced with the items in the array after it. In the above example the where would become this.
WHERE is_active = 'yes' AND is_deleted = 'no'Where statements have the following operators that can be used.
=
!=
startsWith
endsWith
contains
>
>=
<
<=
&&
| |These get translated to the appropriate SQL when used. Here is an example.
<?php
$post->find(array(
'where' => array('(title startsWith ? || title endsWith ?) && time >= ?', 'foo', 'bar', 12345),
));
?>The above would become the following in MySQL
WHERE (title LIKE 'foo%' OR title LIKE '%bar') AND time >= 12345You can do a find on a relationship using the find function outlined above but with the first parameter being the alias of the relationship and the second being the options. Here is an example.
<?php
$post->find('alias', array(
'where' => array('is_active = ?', 1),
));
?>You can change the value of a column by setting it and then running save(), update() or create(). Save will either call update() or insert() depending on if the primary key has been set or not. This relies on auto_increment. Update will update the row within the database and create() will create a new one. Here is an example.
<?
$post->retrieve(1234);
$post->title = 'my new title';
$post->save(); //will call update() to update the existing row
$post = new BlogPosts_Model;
$post->title = 'a new post';
$post->save(); // will call create() to insert a new row
?>You can do this on relationships as well.
If the validators for the fields fail these methods will return false and you will then have to retrieve the errors to display them using $model→getErrors();
It is important to note that when the insert() and update() methods are called, they look for the existence of a preInsert, postInsert, preUpdate, or postUpdate method respectively. These methods have to be defined in the model that the insert or update is being called on and need to be defined as either public or protected in order to work. When these methods are defined the preInsert and preUpdate are called before the actual insert or update and the postInsert and postUpdate are called after the actual insert or update. Using these functions you can do any number of things to prepare for, process, or cleanup before or after the actual insert or update.
Deleting a row
Deleting a row is as simple as calling delete().
<?php
$post->retrieve(1234);
$post->delete();
?>You can also set a where clause in a delete to remove multiple rows at a time from the database.
<?php
$post->delete(array(
'where' => array('is_deleted = ?', 'yes'),
));
?>It is important to note that when the delete() method is called, it looks for the existence of a preDelete or a postDelete method. These methods have to be defined in the model that the insert or update is being called on and need to be defined as either public or protected in order to work. When these methods are defined the preDelete is called before the actual delete and the postDelete is called after the actual delete. Using these functions you can do any number of things to prepare for, process, or cleanup before or after the actual delete.
If saving data fails then you need to get the error messages. There are a couple helper functions including hasErrors, getErrors and getErrorMessages.
hasErrors checks to see if there are errors.
getErrors returns everything about all errors including the error message and the field.
getErrorMessages returns only the error messages.
Models have the potential to work with multiple database types. To add support for other database types besides MySQL you would add a driver to config/drivers/.
At this time there is only one database type available and that is MySQL but there are plans to add more database types including MSSQL and Postgres.
You can access the DB class directly to do custom queries. Check out lib/db.class.php to see which functions are available and how to use them. Here is a quick example.
<?php
/* This will return an associative array of the data returned from the database. */
DB::query('SELECT * FROM table');
?>