Source for file active_record.php
Documentation is available at active_record.php
* File containing the ActiveRecord class
* @version $Id: active_record.php 283 2007-02-17 08:54:28Z john $
* @copyright (c) 2005 John Peterson
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* Load the {@link http://pear.php.net/manual/en/package.pear.php PEAR base class}
require_once('PEAR.php');
* Load the {@link http://pear.php.net/manual/en/package.database.mdb2.php PEAR MDB2 package}
* PEAR::DB is now deprecated.
* (This package(DB) been superseded by MDB2 but is still maintained for bugs and security fixes)
require_once('MDB2.php');
* Base class for the ActiveRecord design pattern
* <p>Each subclass of this class is associated with a database table
* in the Model section of the Model-View-Controller architecture.
* By convention, the name of each subclass is the CamelCase singular
* form of the table name, which is in the lower_case_underscore
* plural notation. For example,
* a table named "order_details" would be associated with a subclass
* of ActiveRecord named "OrderDetail", and a table named "people"
* would be associated with subclass "Person". See the tutorial
* {@tutorial PHPonTrax/naming.pkg}</p>
* <p>For a discussion of the ActiveRecord design pattern, see
* "Patterns of Enterprise
* Application Architecture" by Martin Fowler, pp. 160-164.</p>
* <p>Unit tester: {@link ActiveRecordTest}</p>
* @tutorial PHPonTrax/ActiveRecord.cls
* Reference to the database object
* Reference to the database object returned by
* {@link http://pear.php.net/manual/en/package.database.mdb2.intro-connect.php PEAR MDB2::Connect()}
* {@link http://pear.php.net/manual/en/package.database.mdb2.php PEAR MDB2}
protected static $db = null;
* Description of a row in the associated table in the database
* <p>Retrieved from the RDBMS by {@link set_content_columns()}.
* http://pear.php.net/package/MDB2/docs/2.3.0/MDB2/MDB2_Driver_Reverse_Common.html#methodtableInfo
* DB_common::tableInfo()} for the format. <b>NOTE:</b> Some
* RDBMS's don't return all values.</p>
* <p>An additional element 'human_name' is added to each column
* by {@link set_content_columns()}. The actual value contained
* in each column is stored in an object variable with the name
* given by the 'name' element of the column description for each
* <p><b>NOTE:</b>The information from the database about which
* columns are primary keys is <b>not used</b>. Instead, the
* primary keys in the table are listed in {@link $primary_keys},
* which is maintained independently.</p>
* @see quoted_attributes()
* Array to hold all the info about table columns. Indexed on $table_name.
public static $table_info = array();
* Name of the child class. (this is optional and will automatically be determined)
* Normally set to the singular camel case form of the table name.
* Name of the table in the database associated with the subclass.
* Normally set to the pluralized lower case underscore form of
* the class name by the constructor. May be overridden.
* Name to prefix to the $table_name. May be overridden.
* Name of the database to use, if you are not using the value
* read from file config/database.ini
* Index into the $active_connections array
* Name of the index to use to return or set the current db connection
* Mainly used if you want to connect to different databases between
* Stores the database settings
public static $database_settings = array();
* Stores the active connections. Indexed on $connection_name.
public static $active_connections = array();
* Mode to use when fetching data from database
* http://pear.php.net/package/MDB2/docs/2.3.0/MDB2/MDB2_Driver_Common.html#methodsetFetchMode
* the relevant PEAR MDB2 class documentation}
* Force reconnect to database every page load
* find_all() returns an array of objects,
* each object index is off of this field
* Not yet implemented (page 222 Rails books)
* Composite custom user created objects
* @todo Document this variable
* @todo Document this variable
* @todo Document this variable
* @todo Document this variable
* @todo Document this variable
* @todo Document this property
* Whether or not to auto save defined associations if set
* Whether this object represents a new record
* true => This object was created without reading a row from the
* database, so use SQL 'INSERT' to put it in the database.
* false => This object was a row read from the database, so use
* SQL 'UPDATE' to update database with new values.
* Names of automatic update timestamp columns
* When a row containing one of these columns is updated and
* {@link $auto_timestamps} is true, update the contents of the
* timestamp columns with the current date and time.
* @see $auto_create_timestamps
* Names of automatic create timestamp columns
* When a row containing one of these columns is created and
* {@link $auto_timestamps} is true, store the current date and
* time in the timestamp columns.
* @see $auto_update_timestamps
* Date format for use with auto timestamping
* The format for this should be compatiable with the php date() function.
* http://www.php.net/date
* Time format for use with auto timestamping
* The format for this should be compatiable with the php date() function.
* http://www.php.net/date
* Whether to keep date/datetime fields NULL if not set
* true => If date field is not set it try to preserve NULL
* false => Don't try to preserve NULL if field is already NULL
* SQL aggregate functions that may be applied to the associated
* SQL defines aggregate functions AVG, COUNT, MAX, MIN and SUM.
* Not all of these functions are implemented by all DBMS's
protected $aggregations = array("count","sum","avg","max","min");
* Primary key of the associated table
* Array element(s) name the primary key column(s), as used to
* specify the row to be updated or deleted. To be a primary key
* a column must be listed both here and in {@link }
* $content_columns}. <b>NOTE:</b>This
* field is maintained by hand. It is not derived from the table
* description read from the database.
* Default for how many rows to return from {@link find_all()}
* Pagination how many numbers in the list << < 1 2 3 4 > >>
* @todo Document this variable
* Description of non-fatal errors found
* For every non-fatal error found, an element describing the
* error is added to $errors. Initialized to an empty array in
* {@link valid()} before validating object. When an error
* message is associated with a particular attribute, the message
* should be stored with the attribute name as its key. If the
* message is independent of attributes, store it with a numeric
* An array with all the default error messages.
'inclusion' => "is not included in the list",
'exclusion' => "is reserved",
'invalid' => "is invalid",
'confirmation' => "doesn't match confirmation",
'accepted ' => "must be accepted",
'empty' => "can't be empty",
'blank' => "can't be blank",
'too_long' => "is too long (max is %d characters)",
'too_short' => "is too short (min is %d characters)",
'wrong_length' => "is the wrong length (should be %d characters)",
'taken' => "has already been taken",
'not_a_number' => "is not a number",
'not_an_integer' => "is not an integer"
* An array of all the builtin validation function calls.
'validates_acceptance_of',
'validates_confirmation_of',
'validates_exclusion_of',
'validates_inclusion_of',
'validates_numericality_of',
'validates_uniqueness_of'
* Whether to automatically update timestamps in certain columns
* @see $auto_create_timestamps
* @see $auto_update_timestamps
* Auto insert / update $has_and_belongs_to_many tables
* Auto delete $has_and_belongs_to_many associations
* Transactions (only use if your db supports it)
* This is for transactions only to let query() know that a 'BEGIN' has been executed
private static $begin_executed = false;
* Transactions (only use if your db supports it)
* This will issue a rollback command if any sql fails.
public static $use_transactions = false;
* Keep a log of queries executed if in development env
public static $query_log = array();
* Construct an ActiveRecord object
* <li>Establish a connection to the database</li>
* <li>Find the name of the table associated with this object</li>
* <li>Read description of this table from the database</li>
* <li>Optionally apply update information to column attributes</li>
* @param string[] $attributes Updates to column attributes
* @uses establish_connection()
* @uses set_content_columns()
* @uses set_table_name_using_class_name()
* @uses update_attributes()
# Open the database connection
# If $attributes array is passed in update the class with its contents
# If callback is defined in model run it.
# this could hurt performance...
$this->after_initialize();
* Override get() if they do $model->some_association->field_name
* dynamically load the requested contents from the database.
* @todo Document this API
* @uses get_association_type()
* @uses $has_and_belongs_to_many
* @uses find_all_has_many()
* @uses find_one_belongs_to()
* @uses find_one_has_one()
//error_log("association_type:$association_type");
switch($association_type) {
case "has_and_belongs_to_many":
$this->$key = $composite_object;
//echo "<pre>getting: $key = ".$this->$key."<br></pre>";
* Store column value or description of the table format
* If called with key 'table_name', $value is stored as the
* description of the table format in $content_columns.
* Any other key causes an object variable with the same name to
* be created and stored into. If the value of $key matches the
* name of a column in content_columns, the corresponding object
* variable becomes the content of the column in this row.
* @uses $auto_save_associations
* @uses get_association_type()
* @uses set_content_columns()
function __set($key, $value) {
//echo "setting: $key = $value<br>";
if($key == "table_name") {
# this elseif checks if first its an object if its parent is ActiveRecord
if($association_type == "belongs_to") {
$primary_key = $value->primary_keys[0];
$this->$foreign_key = $value->$primary_key;
# this elseif checks if its an array of objects and if its parent is ActiveRecord
// Assignment to something else, do it
* Override call() to dynamically call the database associations
* @todo Document this API
* @uses get_association_type()
* @uses $has_and_belongs_to_many
function __call($method_name, $parameters) {
# If the method exists, just call it
# ... otherwise, check to see if the method call is one of our
# special Trax methods ...
# ... first check for method names that match any of our explicitly
# declared associations for this model ( e.g. public $has_many = "movies" ) ...
$parameters = $parameters[0];
switch($association_type) {
case "has_and_belongs_to_many":
# check for the [count,sum,avg,etc...]_all magic functions
//echo "calling method: $method_name<br>";
# check for the find_all_by_* magic functions
elseif(strlen($method_name) > 11 && substr($method_name, 0, 11) == "find_all_by") {
//echo "calling method: $method_name<br>";
$result = $this->find_by($method_name, $parameters, "all");
# check for the find_by_* magic functions
elseif(strlen($method_name) > 7 && substr($method_name, 0, 7) == "find_by") {
//echo "calling method: $method_name<br>";
$result = $this->find_by($method_name, $parameters);
# check for find_or_create_by_* magic functions
elseif(strlen($method_name) > 17 && substr($method_name, 0, 17) == "find_or_create_by") {
$result = $this->find_by($method_name, $parameters, "find_or_create");
* Find all records using a "has_and_belongs_to_many" relationship
* (many-to-many with a join table in between). Note that you can also
* specify an optional "paging limit" by setting the corresponding "limit"
* instance variable. For example, if you want to return 10 movies from the
* 5th movie on, you could set $this->movies_limit = "10, 5"
* Parameters: $this_table_name: The name of the database table that has the
* one row you are interested in. E.g. genres
* $other_table_name: The name of the database table that has the
* many rows you are interested in. E.g. movies
* Returns: An array of ActiveRecord objects. (e.g. Movie objects)
* @todo Document this API
private function find_all_habtm($other_table_name, $parameters = null) {
$additional_conditions = null;
# Use any passed-in parameters
$additional_conditions = " AND (". $parameters['conditions']. ")";
} elseif($parameters[0] != "") {
$additional_conditions = " AND (". $parameters[0]. ")";
$order = $parameters['order'];
} elseif($parameters[1] != "") {
$limit = $parameters['limit'];
} elseif($parameters[2] != "") {
$other_object_name = $parameters['class_name'];
$join_table = $parameters['join_table'];
$this_foreign_key = $parameters['foreign_key'];
$other_foreign_key = $parameters['association_foreign_key'];
$finder_sql = $parameters['finder_sql'];
# Instantiate an object to access find_all
$other_class_object = new $other_class_name();
# If finder_sql is specified just use it instead of determining the joins/sql
$conditions = $finder_sql;
# Prepare the join table name primary keys (fields) to do the join on
$other_primary_key = $other_class_object->primary_keys[0];
$this_primary_key_value = "'". $this->$this_primary_key. "'";
$this_primary_key_value = $this->$this_primary_key;
#$this_primary_key_value = 0;
# no primary key value so just return empty array same as find_all()
# Set up the SQL segments
$conditions = "{ $join_table}.{$this_foreign_key} = {$this_primary_key_value}". $additional_conditions;
$joins = "LEFT JOIN {$join_table} ON {$other_table_name}.{$other_primary_key} = {$join_table}.{$other_foreign_key}";
# Get the list of other_class_name objects
return $other_class_object->find_all($conditions, $order, $limit, $joins);
* Find all records using a "has_many" relationship (one-to-many)
* Parameters: $other_table_name: The name of the other table that contains
* many rows relating to this object's id.
* Returns: An array of ActiveRecord objects. (e.g. Contact objects)
* @todo Document this API
$additional_conditions = null;
# Use any passed-in parameters
$additional_conditions = " AND (". $parameters['conditions']. ")";
} elseif($parameters[0] != "") {
$additional_conditions = " AND (". $parameters[0]. ")";
$order = $parameters['order'];
} elseif($parameters[1] != "") {
$limit = $parameters['limit'];
} elseif($parameters[2] != "") {
$foreign_key = $parameters['foreign_key'];
$other_object_name = $parameters['class_name'];
$finder_sql = $parameters['finder_sql'];
# Instantiate an object to access find_all
$other_class_object = new $other_class_name();
# If finder_sql is specified just use it instead of determining the association
$conditions = $finder_sql;
# this should end up being like user_id or account_id but if you specified
# a primaray key other than 'id' it will be like user_field
$foreign_key_value = $this->$this_primary_key;
if($other_class_object->attribute_is_string($foreign_key)) {
$conditions = "{ $foreign_key} = '{ $foreign_key_value}' ";
$conditions = "{ $foreign_key} = { $foreign_key_value}";
#$conditions = "{$foreign_key} = 0";
# no primary key value so just return empty array same as find_all()
$conditions .= $additional_conditions;
# Get the list of other_class_name objects
return $other_class_object->find_all($conditions, $order, $limit, $joins);
* Find all records using a "has_one" relationship (one-to-one)
* (the foreign key being in the other table)
* Parameters: $other_table_name: The name of the other table that contains
* many rows relating to this object's id.
* Returns: An array of ActiveRecord objects. (e.g. Contact objects)
* @todo Document this API
$additional_conditions = null;
# Use any passed-in parameters
//echo "<pre>";print_r($parameters);
$additional_conditions = " AND (". $parameters['conditions']. ")";
} elseif($parameters[0] != "") {
$additional_conditions = " AND (". $parameters[0]. ")";
$order = $parameters['order'];
} elseif($parameters[1] != "") {
$foreign_key = $parameters['foreign_key'];
$other_object_name = $parameters['class_name'];
# Instantiate an object to access find_all
$other_class_object = new $other_class_name();
$foreign_key_value = $this->$this_primary_key;
if($other_class_object->attribute_is_string($foreign_key)) {
$conditions = "{ $foreign_key} = '{ $foreign_key_value}' ";
$conditions = "{ $foreign_key} = { $foreign_key_value}";
#$conditions = "{$foreign_key} = 0";
$conditions .= $additional_conditions;
# Get the list of other_class_name objects
return $other_class_object->find_first($conditions, $order);
* Find all records using a "belongs_to" relationship (one-to-one)
* (the foreign key being in the table itself)
* Parameters: $other_object_name: The singularized version of a table name.
* E.g. If the Contact class belongs_to the
* Customer class, then $other_object_name
* @todo Document this API
$additional_conditions = null;
# Use any passed-in parameters
//echo "<pre>";print_r($parameters);
$additional_conditions = " AND (". $parameters['conditions']. ")";
} elseif($parameters[0] != "") {
$additional_conditions = " AND (". $parameters[0]. ")";
$order = $parameters['order'];
} elseif($parameters[1] != "") {
$foreign_key = $parameters['foreign_key'];
$other_object_name = $parameters['class_name'];
# Instantiate an object to access find_all
$other_class_object = new $other_class_name();
$other_primary_key = $other_class_object->primary_keys[0];
$foreign_key = $other_object_name. "_". $other_primary_key;
$other_primary_key_value = $this->$foreign_key;
if($other_class_object->attribute_is_string($other_primary_key)) {
$conditions = "{ $other_primary_key} = '{ $other_primary_key_value}' ";
$conditions = "{ $other_primary_key} = { $other_primary_key_value}";
#$conditions = "{$other_primary_key} = 0";
$conditions .= $additional_conditions;
# Get the list of other_class_name objects
return $other_class_object->find_first($conditions, $order);
* Implement *_all() functions (SQL aggregate functions)
* Apply one of the SQL aggregate functions to a column of the
* table associated with this object. The SQL aggregate
* functions are AVG, COUNT, MAX, MIN and SUM. Not all DBMS's
* implement all of these functions.
* @param string $agrregrate_type SQL aggregate function to
* apply, suffixed '_all'. The aggregate function is one of
* the strings in {@link $aggregations}.
* @param string[] $parameters Conditions to apply to the
* aggregate function. If present, must be an array of three
* <li>$parameters[0]: If present, expression to apply
* the aggregate function to. Otherwise, '*' will be used.
* <b>NOTE:</b>SQL uses '*' only for the COUNT() function,
* where it means "including rows with NULL in this column".</li>
* <li>$parameters[1]: argument to WHERE clause</li>
* <li>$parameters[2]: joins??? @todo Document this parameter</li>
* @throws {@link ActiveRecordError}
private function aggregate_all($aggregate_type, $parameters = null) {
($parameters[0]) ? $field = $parameters[0] : $field = "*";
# Use any passed-in parameters
if(is_array($parameters[1])) {
} elseif(!is_null($parameters)) {
$conditions = $parameters[1];
if(!empty($joins)) $sql .= " $joins ";
if(!empty($conditions)) $sql .= " WHERE $conditions ";
if(!empty($order)) $sql .= " ORDER BY $order ";
# echo "$aggregate_type sql:$sql<br>";
$this->raise($rs->getMessage());
return $row["agg_result"];
* Returns a the name of the join table that would be used for the two
* tables. The join table name is decided from the alphabetical order
* of the two tables. e.g. "genres_movies" because "g" comes before "m"
* Parameters: $first_table, $second_table: the names of two database tables,
* e.g. "movies" and "genres"
* @todo Document this API
public function get_join_table_name($first_table, $second_table) {
$tables = array($first_table, $second_table);
* Test whether this object represents a new record
* @return boolean Whether this object represents a new record
function is_new_record() {
* get the attributes for a specific column.
* @todo Document this API
function column_for_attribute($attribute) {
if($column['name'] == $attribute) {
* get the columns data type.
* @uses column_for_attribute()
* @todo Document this API
function column_type($attribute) {
if(isset ($column['type'])) {
* Check whether a column exists in the associated table
* When called, {@link $content_columns} lists the columns in
* the table described by this object.
* @param string Name of the column
* @return boolean true=>the column exists; false=>it doesn't
function column_attribute_exists($attribute) {
if($column['name'] == $attribute) {
* Get contents of one column of record selected by id and table
* When called, {@link $id} identifies one record in the table
* identified by {@link $table}. Fetch from the database the
* contents of column $column of this record.
* @param string Name of column to retrieve
* @uses column_attribute_exists()
* @throws {@link ActiveRecordError}
# Run the query to grab a specific columns value.
$result = self::$db->queryOne($sql);
$this->raise($result->getMessage());
* Only used if you want to do transactions and your db supports transactions
* @todo Document this API
self::$db->query("BEGIN");
* Only used if you want to do transactions and your db supports transactions
* @todo Document this API
self::$db->query("COMMIT");
* Only used if you want to do transactions and your db supports transactions
* @todo Document this API
self::$db->query("ROLLBACK");
* Perform an SQL query and return the results
* @param string $sql SQL for the query command
* @return $mdb2->query {@link http://pear.php.net/manual/en/package.database.mdb2.intro-query.php}
* @throws {@link ActiveRecordError}
$rs = & self::$db->query($sql);
if(self::$use_transactions && self::$begin_executed) {
$this->raise($rs->getMessage());
* Implement find_by_*() and =_* methods
* Converts a method name beginning 'find_by_' or 'find_all_by_'
* into a query for rows matching the rest of the method name and
* the arguments to the function. The part of the method name
* after '_by' is parsed for columns and logical relationships
* (AND and OR) to match. For example, the call
* SELECT * ... WHERE fname='Ben'
* find_by_fname_and_lname('Ben','Dover')
* SELECT * ... WHERE fname='Ben' AND lname='Dover'
private function find_by($method_name, $parameters, $find_type = null) {
if($find_type == "find_or_create") {
} elseif($find_type == "all") {
$method_name = substr(strtolower($method_name), $explode_len);
$method_parts = explode("|", str_replace("_and_", "|AND|", $method_name));
if(count($method_parts)) {
$create_fields = array();
foreach($method_parts as $part) {
"'". $parameters[$param_index]. "'" :
$parameters[$param_index];
$create_fields[$part] = $parameters[$param_index];
$conditions .= "{ $part} = { $value}";
# If last param exists and is a string set it as the ORDER BY clause
# or if the last param is an array set it as the $options
if($last_param = $parameters[++$param_index]) {
if(is_string($last_param)) {
$options['order'] = $last_param;
} elseif(is_array($last_param)) {
if($options['conditions'] && $conditions) {
$options['conditions'] = "(".$options['conditions'].") AND (".$conditions.")";
$options['conditions'] = $conditions;
# Now do the actual find with condtions from above
if($find_type == "find_or_create") {
# see if we can find a record with specified parameters
$object = $this->find($options);
# we found a record with the specified parameters so return it
} elseif(count($create_fields)) {
# can't find a record with specified parameters so create a new record
foreach($create_fields as $field => $value) {
return $this->find($options);
} elseif($find_type == "all") {
return $this->find($options);
* Builds a sql statement.
* @uses $rows_per_page_default
function build_sql($conditions = null, $order = null, $limit = null, $joins = null) {
# this is if they passed in an associative array to emulate
if(is_array($conditions)) {
if(@array_key_exists("per_page", $conditions) && !is_numeric($conditions['per_page'])) {
# If conditions wasn't in the array set it to null
if(is_array($conditions)) {
# Test source of SQL for query
if(stristr($conditions, "SELECT")) {
# SQL completely specified in argument so use it as is
# If select fields not specified just do a SELECT *
# SQL will be built from specifications in argument
# If join specified, include it
# If conditions specified, include them
if(!is_null($conditions)) {
$sql .= "WHERE $conditions ";
# If ordering specified, include it
$sql .= "ORDER BY $order ";
# Is output to be generated in pages?
if(is_numeric($limit) || is_numeric($offset) || is_numeric($per_page)) {
$this->rows_per_page = $limit;
if(is_numeric($per_page)) {
$this->rows_per_page = $per_page;
# Default for rows_per_page:
if ($this->rows_per_page <= 0) {
# Only use request's page if you are calling from find_all_with_pagination() and if it is int
if(strval(intval($_REQUEST['page'])) == $_REQUEST['page']) {
$this->page = $_REQUEST['page'];
# Set the LIMIT string segment for the SQL
$offset = ($this->page - 1) * $this->rows_per_page;
$sql .= "LIMIT { $this->rows_per_page} OFFSET { $offset}";
# $sql .= "LIMIT $offset, $this->rows_per_page";
# Set number of total pages in result set
if($count = $this->count_all($this->primary_keys[0], $conditions, $joins)) {
$this->pages = (($count % $this->rows_per_page) == 0)
: floor($count / $this->rows_per_page) + 1;
* Return rows selected by $conditions
* If no rows match, an empty array is returned.
* @param string SQL to use in the query. If
* $conditions contains "SELECT", then $order, $limit and
* $joins are ignored and the query is completely specified by
* $conditions. If $conditions is omitted or does not contain
* "SELECT", "SELECT * FROM" will be used. If $conditions is
* specified and does not contain "SELECT", the query will
* include "WHERE $conditions". If $conditions is null, the
* entire table is returned.
* @param string Argument to "ORDER BY" in query.
* If specified, the query will include
* "ORDER BY $order". If omitted, no ordering will be
* @param integer[] Page, rows per page???
* @todo Document the $limit and $joins parameters
* @return object[] Array of objects of the same class as this
* object, one object for each row returned by the query.
* If the column 'id' was in the results, it is used as the key
* for that object in the array.
* @throws {@link ActiveRecordError}
function find_all($conditions = null, $order = null, $limit = null, $joins = null) {
//error_log("find_all(".(is_null($conditions)?'null':$conditions)
// .', ' . (is_null($order)?'null':$order)
// .', ' . (is_null($limit)?'null':var_export($limit,true))
// .', ' . (is_null($joins)?'null':$joins).')');
# Placed the sql building code in a separate function
$sql = $this->build_sql($conditions, $order, $limit, $joins);
# echo "ActiveRecord::find_all() - sql: $sql\n<br>";
# error_log("ActiveRecord::find_all -> $sql");
$this->raise($rs->getMessage());
while($row = $rs->fetchRow()) {
$object = new $class_name();
$object->new_record = false;
foreach($row as $field => $value) {
$object->$field = $value;
$objects[$objects_key] = $object;
# If callback is defined in model run it.
# this will probably hurt performance...
if(method_exists($object, 'after_find')) {
* Find row(s) with specified value(s)
* Find all the rows in the table which match the argument $id.
* Return zero or more objects of the same class as this
* class representing the rows that matched the argument.
* @param mixed[] $id If $id is an array then a query will be
* generated selecting all of the array values in column "id".
* If $id is a string containing "=" then the string value of
* $id will be inserted in a WHERE clause in the query. If $id
* is a scalar not containing "=" then a query will be generated
* selecting the first row WHERE id = '$id'.
* <b>NOTE</b> The column name "id" is used regardless of the
* value of {@link $primary_keys}. Therefore if you need to
* select based on some column other than "id", you must pass a
* string argument ready to insert in the SQL SELECT.
* @param string $order Argument to "ORDER BY" in query.
* If specified, the query will include "ORDER BY
* $order". If omitted, no ordering will be applied.
* @param integer[] $limit Page, rows per page???
* @param string $joins ???
* @todo Document the $limit and $joins parameters
* @return mixed Results of query. If $id was a scalar then the
* result is an object of the same class as this class and
* matching $id conditions, or if no row matched the result is
* If $id was an array then the result is an array containing
* objects of the same class as this class and matching the
* conditions set by $id. If no rows matched, the array is
* @throws {@link ActiveRecordError}
function find($id, $order = null, $limit = null, $joins = null) {
# passed in array of numbers array(1,2,4,23)
"'". implode("','", $id). "'" :
$options['conditions'] = "{ $primary_key} IN({ $primary_key_values}) ";
# passed in an options array
} elseif(stristr($id, "=")) {
# has an "=" so must be a WHERE clause
$options['conditions'] = $id;
# find an single record with id = $id
$options['conditions'] = "{ $primary_key} = { $primary_key_value}";
if(!is_null($order)) $options['order'] = $order;
if(!is_null($limit)) $options['limit'] = $limit;
if(!is_null($joins)) $options['joins'] = $joins;
* Return first row selected by $conditions
* If no rows match, null is returned.
* @param string $conditions SQL to use in the query. If
* $conditions contains "SELECT", then $order, $limit and
* $joins are ignored and the query is completely specified by
* $conditions. If $conditions is omitted or does not contain
* "SELECT", "SELECT * FROM" will be used. If $conditions is
* specified and does not contain "SELECT", the query will
* include "WHERE $conditions". If $conditions is null, the
* entire table is returned.
* @param string $order Argument to "ORDER BY" in query.
* If specified, the query will include
* "ORDER BY $order". If omitted, no ordering will be
* FIXME This parameter doesn't seem to make sense
* @param integer[] $limit Page, rows per page??? @todo Document this parameter
* FIXME This parameter doesn't seem to make sense
* @param string $joins ??? @todo Document this parameter
* @return mixed An object of the same class as this class and
* matching $conditions, or null if none did.
* @throws {@link ActiveRecordError}
function find_first($conditions = null, $order = null, $limit = 1, $joins = null) {
if(is_array($conditions)) {
$options['conditions'] = $conditions;
if(!is_null($order)) $options['order'] = $order;
if(!is_null($limit)) $options['limit'] = $limit;
if(!is_null($joins)) $options['joins'] = $joins;
$result = @current($this->find_all($options));
return (is_object($result) ? $result : null);
* Return all the rows selected by the SQL argument
* If no rows match, an empty array is returned.
* @param string $sql SQL to use in the query.
function find_by_sql($sql) {
* Reloads the attributes of this object from the database.
* @uses get_primary_key_conditions()
* @todo Document this API
function reload($conditions = null) {
if(is_null($conditions)) {
$object = $this->find($conditions);
foreach($object as $key => $value) {
* Loads into current object values from the database.
function load($conditions = null) {
return $this->reload($conditions);
* @todo Document this API. What's going on here? It appears to
* either create a row with all empty values, or it tries
* to recurse once for each attribute in $attributes.
* Creates an object, instantly saves it as a record (if the validation permits it).
* If the save fails under validations it returns false and $errors array gets set.
function create($attributes, $dont_validate = false) {
$object = new $class_name();
$result = $object->save($attributes, $dont_validate);
return ($result ? $object : false);
* Finds the record from the passed id, instantly saves it with the passed attributes
* (if the validation permits it). Returns true on success and false on error.
* @todo Document this API
function update($id, $attributes, $dont_validate = false) {
foreach($id as $update_id) {
$this->update($update_id, $attributes[$update_id], $dont_validate);
$object = $this->find($id);
return $object->save($attributes, $dont_validate);
* Updates all records with the SET-part of an SQL update statement in updates and
* returns an integer with the number of rows updates. A subset of the records can
* be selected by specifying conditions.
* $model->update_all("category = 'cooldude', approved = 1", "author = 'John'");
* @throws {@link ActiveRecordError}
* @todo Document this API
function update_all($updates, $conditions = null) {
$result = $this->query($sql);
$this->raise($result->getMessage());
* Save without valdiating anything.
* @todo Document this API
function save_without_validation($attributes = null) {
return $this->save($attributes, true);
* Create or update a row in the table with specified attributes
* @param string[] $attributes List of name => value pairs giving
* name and value of attributes to set.
* @param boolean $dont_validate true => Don't call validation
* routines before saving the row. If false or omitted, all
* applicable validation routines are called.
* @uses add_record_or_update_record()
* @uses update_attributes()
* <li>true => row was updated or inserted successfully</li>
* <li>false => insert failed</li>
function save($attributes = null, $dont_validate = false) {
//error_log("ActiveRecord::save() \$attributes="
// . var_export($attributes,true));
if($dont_validate || $this->valid()) {
* Create or update a row in the table
* If this object represents a new row in the table, insert it.
* Otherwise, update the exiting row. before_?() and after_?()
* routines will be called depending on whether the row is new.
* <li>true => row was updated or inserted successfully</li>
* <li>false => insert failed</li>
private function add_record_or_update_record() {
//error_log('add_record_or_update_record()');
* Insert a new row in the table associated with this object
* Build an SQL INSERT statement getting the table name from
* {@link $table_name}, the column names from {@link
* $content_columns} and the values from object variables.
* Send the insert to the RDBMS.
* @uses add_habtm_records()
* <li>true => row was inserted successfully</li>
* <li>false => insert failed</li>
* @throws {@link ActiveRecordError}
private function add_record() {
self::$db->loadModule('Extended', null, true);
# $primary_key_value may either be a quoted integer or php null
if($this->is_error($primary_key_value)) {
$this->raise($primary_key_value->getMessage());
$fields = @implode(', ', array_keys($attributes));
$values = @implode(', ', array_values($attributes));
//echo "add_record: SQL: $sql<br>";
//error_log("add_record: SQL: $sql");
$result = $this->query($sql);
$this->raise($results->getMessage());
# $id is now equivalent to the value in the id field that was inserted
if($this->is_error($primary_key_value)) {
$this->raise($primary_key_value->getMessage());
$this->$primary_key = $primary_key_value;
if($primary_key_value != '') {
return ($result && $habtm_result);
* Update the row in the table described by this object
* The primary key attributes must exist and have appropriate
* non-null values. If a column is listed in {@link
* $content_columns} but no attribute of that name exists, the
* column will be set to the null string ''.
* @todo Describe habtm automatic update
* @uses get_updates_sql()
* @uses get_primary_key_conditions()
* @uses update_habtm_records()
* <li>true => row was updated successfully</li>
* <li>false => update failed</li>
* @throws {@link ActiveRecordError}
private function update_record() {
//error_log('update_record()');
//echo "update_record:$sql<br>";
//error_log("update_record: SQL: $sql");
$result = $this->query($sql);
$this->raise($results->getMessage());
$primary_key_value = $this->$primary_key;
if($primary_key_value > 0) {
return ($result && $habtm_result);
* Loads the model values into composite object
* @todo Document this API
private function get_composite_object($name) {
$composite_object = null;
$composite_attributes = array();
$class_name = Inflector::classify(($this->composed_of[$name]['class_name'] ?
if(is_array($mappings)) {
foreach($mappings as $database_name => $composite_name) {
$composite_attributes[$composite_name] = $this->$database_name;
$composite_attributes[$name] = $this->$name;
if(class_exists($class_name)) {
$composite_object = new $class_name;
if($composite_object->auto_map_attributes !== false) {
//echo "auto_map_attributes<br>";
foreach($composite_attributes as $name => $value) {
$composite_object->$name = $value;
if(method_exists($composite_object, '__construct')) {
//echo "calling constructor<br>";
$composite_object->__construct($composite_attributes);
return $composite_object;
* returns the association type if defined in child class or null
* @todo Document this API
* @uses $has_and_belongs_to_many
* @return mixed Association type, one of the following:
* <li>"has_and_belongs_to_many"</li>
* if an association exists, or null if no association
function get_association_type($association_name) {
if(preg_match("/\b$association_name\b/", $this->has_many)) {
if(array_key_exists($association_name, $this->has_many)) {
if(preg_match("/\b$association_name\b/", $this->has_one)) {
} elseif(is_array($this->has_one)) {
if(array_key_exists($association_name, $this->has_one)) {
if(preg_match("/\b$association_name\b/", $this->belongs_to)) {
if(array_key_exists($association_name, $this->belongs_to)) {
$type = "has_and_belongs_to_many";
$type = "has_and_belongs_to_many";
* Saves any associations objects assigned to this instance
* @uses $auto_save_associations
* @todo Document this API
private function save_associations() {
if(is_object($object_or_array)) {
} elseif(is_array($object_or_array)) {
foreach($object_or_array as $object) {
* save the association to the database
* @todo Document this API
private function save_association($object, $type) {
if(is_object($object) && get_parent_class($object) == __CLASS__ && $type) {
//echo get_class($object)." - type:$type<br>";
$foreign_key = Inflector::singularize($this->table_name). "_". $primary_key;
$object->$foreign_key = $this->$primary_key;
//echo "fk:$foreign_key = ".$this->$primary_key."<br>";
* Deletes the record with the given $id or if you have done a
* $model = $model->find($id), then $model->delete() it will delete
* the record it just loaded from the find() without passing anything
* to delete(). If an array of ids is provided, all ids in array are deleted.
* @todo Document this API
function delete($id = null) {
$primary_key_value = null;
# Primary key's where clause from already loaded values
$deleted_ids[] = $this->$primary_key;
} elseif(!is_array($id)) {
$conditions = "{ $primary_key} = { $id}";
} elseif(is_array($id)) {
"'". implode("','", $id). "'" :
$conditions = "{ $primary_key} IN ({ $ids}) ";
if(is_null($conditions)) {
$this->errors[] = "No conditions specified to delete on.";
foreach($deleted_ids as $id) {
foreach($habtms as $other_table_name) {
* Delete from table all rows that match argument
* Delete the row(s), if any, matching the argument.
* @param string $conditions SQL argument to "WHERE" describing
* <li>true => One or more rows were deleted</li>
* <li>false => $conditions was omitted</li>
* @throws {@link ActiveRecordError}
function delete_all($conditions = null) {
if(is_null($conditions)) {
$this->errors[] = "No conditions specified to delete on.";
$this->raise($rs->getMessage());
* @uses $has_and_belongs_to_many
* @todo Document this API
private function set_habtm_attributes($attributes) {
if(is_array($attributes)) {
foreach($attributes as $key => $habtm_array) {
if(is_array($habtm_array)) {
* @todo Document this API
private function update_habtm_records($this_foreign_value) {
* @throws {@link ActiveRecordError}
* @todo Document this API
private function add_habtm_records($this_foreign_value) {
foreach($this->habtm_attributes as $other_table_name => $other_foreign_values) {
$other_foreign_key = Inflector::singularize($other_table_name). "_id";
$this_foreign_key = Inflector::singularize($this->table_name). "_id";
foreach($other_foreign_values as $other_foreign_value) {
$attributes[$this_foreign_key] = $this_foreign_value;
$attributes[$other_foreign_key] = $other_foreign_value;
$fields = @implode(', ', array_keys($attributes));
$values = @implode(', ', array_values($attributes));
$sql = "INSERT INTO $table_name ($fields) VALUES ($values)";
//echo "add_habtm_records: SQL: $sql<br>";
$result = $this->query($sql);
$this->raise($result->getMessage());
* @throws {@link ActiveRecordError}
* @todo Document this API
private function delete_habtm_records($this_foreign_value) {
private function delete_all_habtm_records($other_table_name, $this_foreign_value) {
if($other_table_name && $this_foreign_value > 0) {
$this_foreign_key = Inflector::singularize($this->table_name). "_id";
$sql = "DELETE FROM { $habtm_table_name} WHERE { $this_foreign_key} = { $this_foreign_value}";
//echo "delete_all_habtm_records: SQL: $sql<br>";
$result = $this->query($sql);
$this->raise($result->getMessage());
* Apply automatic timestamp updates
* If automatic timestamps are in effect (as indicated by
* {@link $auto_timestamps} == true) and the column named in the
* $field argument is of type "timestamp" and matches one of the
* names in {@link auto_create_timestamps} or {@link
* auto_update_timestamps}(as selected by {@link $new_record}),
* then return the current date and time as a string formatted
* to insert in the database. Otherwise return $value.
* @uses $auto_create_timestamps
* @uses $auto_update_timestamps
* @param string $field Name of a column in the table
* @param mixed $value Value to return if $field is not an
* automatic timestamp column
* @return mixed Current date and time or $value
private function check_datetime($field, $value) {
if(($field_info['name'] == $field) && stristr($field_info['type'], "date")) {
} elseif($this->preserve_null_dates && is_null($value) && !stristr($field_info['flags'], "not_null")) {
} elseif($this->preserve_null_dates && is_null($value) && !stristr($field_info['flags'], "not_null")) {
* Update object attributes from list in argument
* The elements of $attributes are parsed and assigned to
* attributes of the ActiveRecord object. Date/time fields are
* treated according to the
* {@tutorial PHPonTrax/naming.pkg#naming.naming_forms}.
* @param string[] $attributes List of name => value pairs giving
* name and value of attributes to set.
* @uses $auto_save_associations
* @todo Figure out and document how datetime fields work
function update_attributes($attributes) {
//error_log('update_attributes()');
if(is_array($attributes)) {
$datetime_fields = array();
// Test each attribute to be updated
// and process according to its type
foreach($attributes as $field => $value) {
# datetime / date parts check
if(preg_match('/^\w+\(.*i\)$/i', $field)) {
// The name of this attribute ends in "(?i)"
// indicating that it's part of a date or time
$datetime_field = substr($field, 0, strpos($field, "("));
if(!in_array($datetime_field, $datetime_fields)) {
$datetime_fields[] = $datetime_field;
# this elseif checks if first its an object if its parent is ActiveRecord
if($association_type == "belongs_to") {
$primary_key = $value->primary_keys[0];
$foreign_key = Inflector::singularize($value->table_name). "_". $primary_key;
$this->$foreign_key = $value->$primary_key;
# this elseif checks if its an array of objects and if its parent is ActiveRecord
// Just a simple attribute, copy it
// If any date/time fields were found, assign the
// accumulated values to corresponding attributes
if(count($datetime_fields)) {
foreach($datetime_fields as $datetime_field) {
if($attributes[$datetime_field."(1i)"]
&& $attributes[$datetime_field."(2i)"]
&& $attributes[$datetime_field."(3i)"]) {
$datetime_value = $attributes[$datetime_field."(1i)"]
. "-" . $attributes[$datetime_field."(2i)"]
. "-" . $attributes[$datetime_field."(3i)"];
if($attributes[$datetime_field."(4i)"]
&& $attributes[$datetime_field."(5i)"]) {
$datetime_value .= $attributes[$datetime_field."(4i)"]
. ":" . $attributes[$datetime_field."(5i)"];
if($datetime_value = trim($datetime_value)) {
$datetime_value = date($datetime_format, strtotime($datetime_value));
//error_log("($field) $datetime_field = $datetime_value");
$this->$datetime_field = $datetime_value;
* If a composite object was specified via $composed_of, then its values
* mapped to the model will overwrite the models values.
function update_composite_attributes() {
$composite_object = $this->$name;
if(is_array($options) && is_object($composite_object)) {
if(is_array($options['mapping'])) {
foreach($options['mapping'] as $database_name => $composite_name) {
$this->$database_name = $composite_object->$composite_name;
* Return pairs of column-name:column-value
* Return the contents of the object as an array of elements
* where the key is the column name and the value is the column
* value. Relies on a previous call to
* {@link set_content_columns()} for information about the format
* @see set_content_columns
* @see quoted_attributes()
function get_attributes() {
//echo "attribute: $info[name] -> {$this->$info[name]}<br>";
$attributes[$column['name']] = $this->$column['name'];
* Return pairs of column-name:quoted-column-value
* Return pairs of column-name:quoted-column-value where the key
* is the column name and the value is the column value with
* automatic timestamp updating applied and characters special to
* If $attributes is null or omitted, return all columns as
* currently stored in {@link content_columns()}. Otherwise,
* return the name:value pairs in $attributes.
* @param string[] $attributes Name:value pairs to return.
* If null or omitted, return the column names and values
* of the object as stored in $content_columns.
* @see set_content_columns()
function quoted_attributes($attributes = null) {
if(is_null($attributes)) {
foreach($attributes as $name => $value) {
* Quotes a single attribute for use in an sql statement.
function quote_attribute($attribute, $value = null) {
$value = is_null($value) ? $this->$attribute : $value;
if(isset ($column['mdb2type'])) {
$type = $column['mdb2type'];
"text" : is_float($attribute) ? "float" : "integer";
$value = self::$db->quote($value, $type);
if($value === 'NULL' && stristr($column['flags'], "not_null")) {
* Escapes a string for use in an sql statement.
function escape($string) {
return(self::$db->escape($string));
* Return column values for SQL insert statement
* Return an array containing the column names and values of this
* object, filtering out the primary keys, which are not set.
* @uses quoted_attributes()
foreach($attributes as $key => $value) {
if(!in_array($key, $this->primary_keys) || ($value != "''" && isset ($value))) {
* Return argument for a "WHERE" clause specifying this row
* Returns a string which specifies the column(s) and value(s)
* which describe the primary key of this row of the associated
* table. The primary key must be one or more attributes of the
* object and must be listed in {@link $content_columns} as
* Example: if $primary_keys = array("id", "ssn") and column "id"
* has value "5" and column "ssn" has value "123-45-6789" then
* the string "id = 5 AND ssn = '123-45-6789'" would be returned.
* @uses quoted_attributes()
* @return string Column name = 'value' [ AND name = 'value']...
function get_primary_key_conditions($operator = "=") {
if(count($attributes) > 0) {
# run through our fields and join them with their values
foreach($attributes as $key => $value) {
if(in_array($key, $this->primary_keys) && isset ($value) && $value != "''") {
$conditions[] = "{ $key} { $operator} { $value}";
$conditions = implode(" AND ", $conditions);
* Return column values of object formatted for SQL update statement
* Return a string containing the column names and values of this
* object in a format ready to be inserted in a SQL UPDATE
* statement. Automatic update has been applied to timestamps if
* enabled and characters special to SQL have been quoted.
* @uses quoted_attributes()
* @return string Column name = 'value', ... for all attributes
function get_updates_sql() {
if(count($attributes) > 0) {
# run through our fields and join them with their values
foreach($attributes as $key => $value) {
if($key && isset($value) && !in_array($key, $this->primary_keys)) {
$updates[] = "$key = $value";
$updates = implode(", ", $updates);
* Set {@link $table_name} from the class name of this object
* By convention, the name of the database table represented by
* this object is derived from the name of the class.
* @uses Inflector::tableize()
function set_table_name_using_class_name() {
$this->table_name = Inflector::tableize($class_name);
* Get class name of child object
* this will return the manually set name or get_class($this)
* @return string child class name
private function get_class_name() {
* Populate object with information about the table it represents
* http://pear.php.net/manual/en/package.database.db.db-common.tableinfo.php
* DB_common::tableInfo()} to get a description of the table and
* store it in {@link $content_columns}. Add a more human
* friendly name to the element for each column.
* @uses Inflector::humanize()
* @param string $table_name Name of table to get information about
function set_content_columns($table_name) {
if(isset(self::$table_info[$table_name])) {
self::$db->loadModule('Reverse', null, true);
$this->content_columns[$i++ ]['human_name'] = Inflector::humanize($column['name']);
* Returns the autogenerated id from the last insert query
* @throws {@link ActiveRecordError}
function get_insert_id() {
// fetch the last inserted id via autoincrement or current value of a sequence
if(self::$db->supports('auto_increment') === true) {
$this->raise($id->getMessage());
* Open a database connection if one is not currently open
* The name of the database normally comes from
* $database_settings which is set in {@link
* environment.php} by reading file config/database.ini. The
* database name may be overridden by assigning a different name
* to {@link $database_name}.
* If there is a connection now open, as indicated by the saved
* value of a MDB2 object in $active_connections[$connection_name], and
* {@link force_reconnect} is not true, then set the database
* If there is no connection, open one and save a reference to
* it in $active_connections[$connection_name].
* @uses $active_connections
* @throws {@link ActiveRecordError}
function establish_connection() {
$connection_settings = array();
$connection_options = array();
# Use a different custom sections settings ?
if(array_key_exists("use", self::$database_settings[$this->connection_name])) {
$connection_settings = self::$database_settings[self::$database_settings[$this->connection_name]['use']];
# Custom defined db settings in database.ini
# Just use the current TRAX_ENV's environment db settings
# $this->connection_name's default value is TRAX_ENV so
# if should never really get here unless override $this->connection_name
# and you define a custom db section in database.ini and it can't find it.
$connection_settings = self::$database_settings[TRAX_ENV];
# Override database name if param is set
# Set optional Pear parameters
if(isset($connection_settings['persistent'])) {
$connection_options['persistent'] = $connection_settings['persistent'];
# Connect to the database and throw an error if the connect fails.
$connection =& MDB2::Connect($connection_settings, $connection_options);
//static $connect_cnt; $connect_cnt++; error_log("connection #".$connect_cnt);
# For Postgres schemas (http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html)
if(isset($connection_settings['schema_search_path'])){
# Set the schema search path to a string of comma-separated schema names.
# First strip out all the whitespace
$connection->query('SET search_path TO '. preg_replace('/\s+/', '', $connection_settings['schema_search_path']));
self::$db = & $connection;
$this->raise($connection->getMessage());
* Determine if passed in attribute (table column) is a string
* @param string $attribute Name of the table column
* @uses column_for_attribute()
function attribute_is_string($attribute, $column = null) {
switch(strtolower($column['mdb2type'])) {
* Determine if passed in name is a composite class or not
* @param string $name Name of the composed_of mapping
private function is_composite($name) {
* Runs validation routines for update or create
* @uses after_validation();
* @uses after_validation_on_create();
* @uses after_validation_on_update();
* @uses before_validation();
* @uses before_validation_on_create();
* @uses before_validation_on_update();
* @uses validate_model_attributes();
* @uses validate_builtin();
* @uses validate_on_create();
* <li>true => Valid, no errors found.
* {@link $errors} is empty</li>
* <li>false => Not valid, errors in {@link $errors}</li>
# first clear the errors array
$this->validate_on_update_builtin();
return count($this->errors) ? false : true;
* Call every method named "validate_*()" where * is a column name
* Find and call every method named "validate_something()" where
* "something" is the name of a column. The "validate_something()"
* functions are expected to return an array whose first element
* is true or false (indicating whether or not the validation
* succeeded), and whose second element is the error message to
* display if the first element is false.
* <li>true => Valid, no errors found.
* {@link $errors} is empty</li>
* <li>false => Not valid, errors in {@link $errors}.
* $errors is an array whose keys are the names of columns,
* and the value of each key is the error message returned
* by the corresponding validate_*() method.</li>
function validate_model_attributes() {
foreach($methods as $method) {
if(preg_match('/^validate_(.+)/', $method, $matches)) {
# If we find, for example, a method named validate_name, then
# we know that that function is validating the 'name' attribute
# (as found in the (.+) part of the regular expression above).
$validate_on_attribute = $matches[1];
# Check to see if the string found (e.g. 'name') really is
# in the list of attributes for this object...
if(array_key_exists($validate_on_attribute, $attrs)) {
# ...if so, then call the method to see if it validates to true...
$result = $this->$method();
# $result[0] is true if validation went ok, false otherwise
# $result[1] is the error message if validation failed
if($result[0] == false) {
# ... and if not, then validation failed
# Mark the corresponding entry in the error array by
# putting the error message in for the attribute,
# e.g. $this->errors['name'] = "can't be empty"
# when 'name' was an empty string.
$this->errors[$validate_on_attribute] = $result[1];
* Overwrite this method for validation checks on all saves and
* use $this->errors[] = "My error message."; or
* for invalid attributes $this->errors['attribute'] = "Attribute is invalid.";
* @todo Document this API
* Override this method for validation checks used only on creation.
* @todo Document this API
function validate_on_create() {}
* Override this method for validation checks used only on updates.
* @todo Document this API
function validate_on_update() {}
* Is called before validate().
* @todo Document this API
function before_validation() {}
* Is called after validate().
* @todo Document this API
function after_validation() {}
* Is called before validate() on new objects that haven't been saved yet (no record exists).
* @todo Document this API
function before_validation_on_create() {}
* Is called after validate() on new objects that haven't been saved yet (no record exists).
* @todo Document this API
function after_validation_on_create() {}
* Is called before validate() on existing objects that has a record.
* @todo Document this API
function before_validation_on_update() {}
* Is called after validate() on existing objects that has a record.
* @todo Document this API
function after_validation_on_update() {}
* Is called before save() (regardless of whether its a create or update save)
* @todo Document this API
function before_save() {}
* Is called after save (regardless of whether its a create or update save).
* @todo Document this API
* Is called before save() on new objects that havent been saved yet (no record exists).
* @todo Document this API
function before_create() {}
* Is called after save() on new objects that havent been saved yet (no record exists).
* @todo Document this API
function after_create() {}
* Is called before save() on existing objects that has a record.
* @todo Document this API
function before_update() {}
* Is called after save() on existing objects that has a record.
* @todo Document this API
function after_update() {}
* Is called before delete().
* @todo Document this API
function before_delete() {}
* Is called after delete().
* @todo Document this API
function after_delete() {}
* Validates any builtin validates_* functions defined as
* class variables in child model class.
* public $validates_presence_of = array(
* 'message' => "is not optional.",
* @uses $builtin_validation_functions
function validate_builtin() {
$validation_name = $this->$method_name;
if(is_string($validation_name)) {
$validation_name = explode(",", $validation_name);
if(method_exists($this, $method_name) && is_array($validation_name)) {
foreach($validation_name as $attribute_name => $options) {
if(!is_array($options)) {
$attribute_name = $options;
$attribute_name = trim($attribute_name);
$on = array_key_exists('on', $options) ?
$message = array_key_exists('message', $options) ?
$options['message'] : null;
case 'validates_acceptance_of':
$accept = array_key_exists('accept', $options) ? $options['accept'] : 1;
$parameters = array($attribute_name, $message, $accept);
case 'validates_confirmation_of':
$parameters = array($attribute_name, $message);
case 'validates_exclusion_of':
$in = array_key_exists('in', $options) ? $options['in'] : array();
$parameters = array($attribute_name, $in, $message);
case 'validates_format_of':
$with = array_key_exists('with', $options) ? $options['with'] : '';
$parameters = array($attribute_name, $with, $message);
case 'validates_inclusion_of':
$in = array_key_exists('in', $options) ? $options['in'] : array();
$parameters = array($attribute_name, $in, $message);
case 'validates_length_of':
$parameters = array($attribute_name, $options);
case 'validates_numericality_of':
$only_integer = array_key_exists('only_integer', $options) ?
$options['only_integer'] : false;
$allow_null = array_key_exists('allow_null', $options) ?
$options['allow_null'] : false;
$parameters = array($attribute_name, $message, $only_integer, $allow_null);
case 'validates_presence_of':
$parameters = array($attribute_name, $message);
case 'validates_uniqueness_of':
$parameters = array($attribute_name, $message);
} elseif($on == 'save') {
# error_log("calling $method_name(".implode(",",$parameters).")");
call_user_func_array(array($this, $method_name), $parameters);
* Validates that a checkbox is clicked.
* eg. validates_acceptance_of('eula')
* @param string|array $attribute_names
function validates_acceptance_of($attribute_names, $message = null, $accept = 1) {
foreach((array) $attribute_names as $attribute_name) {
if($this->$attribute_name != $accept) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that a field has the same value as its corresponding confirmation field.
* eg. validates_confirmation_of('password')
* @param string|array $attribute_names
function validates_confirmation_of($attribute_names, $message = null) {
foreach((array) $attribute_names as $attribute_name) {
$attribute_confirmation = $attribute_name . '_confirmation';
if($this->$attribute_confirmation != $this->$attribute_name) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes are NOT in an array of elements.
* eg. validates_exclusion_of('age, 'in' => array(13, 19))
* @param string|array $attribute_names
* @param mixed $in array(1,2,3,4,5) or string 1..5
function validates_exclusion_of($attribute_names, $in = array(), $message = null) {
foreach((array) $attribute_names as $attribute_name) {
list($minimum, $maximum) = explode('..', $in);
if($this->$attribute_name >= $minimum && $this->$attribute_name <= $maximum) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
} elseif(is_array($in)) {
if(in_array($this->$attribute_name, $in)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes matches a regular expression
* eg. validates_format_of('email', '/^(+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i')
* @param string|array $attribute_names
function validates_format_of($attribute_names, $regex, $message = null) {
foreach((array) $attribute_names as $attribute_name) {
$value = $this->$attribute_name;
if(!preg_match($regex, $value)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes are in an array of elements.
* eg. validates_inclusion_of('gender', array('m', 'f'))
* @param string|array $attribute_names
* @param mixed $in array(1,2,3,4,5) or string 1..5
function validates_inclusion_of($attribute_names, $in = array(), $message = null) {
foreach((array) $attribute_names as $attribute_name) {
list($minimum, $maximum) = explode('..', $in);
if(!($this->$attribute_name >= $minimum && $this->$attribute_name <= $maximum)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
} elseif(is_array($in)) {
if(!in_array($this->$attribute_name, $in)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes are of some length
* eg. validates_length_of('password', array('minimum' => 8))
* @param string|array $attribute_names
function validates_length_of($attribute_names, $options = array(
'too_short' => null, 'too_long' => null, 'wrong_length' => null, 'message' => null)) {
# Convert 'in' to 'minimum' and 'maximum'
if(isset($options['in'])) {
list($options['minimum'], $options['maximum']) = explode('..', $options['in']);
# If 'message' is set see if we need to override other messages
if(isset($options['message'])) {
if(!isset($options['too_short'])) $options['too_short'] = $options['message'];
if(!isset($options['too_long'])) $options['too_long'] = $options['message'];
if(!isset($options['wrong_length'])) $options['wrong_length'] = $options['message'];
foreach((array) $attribute_names as $attribute_name) {
# Attribute string length
$len = strlen($this->$attribute_name);
$attribute_human = Inflector::humanize($attribute_name);
# If you have set the min length option
if(isset ($options['minimum'])) {
if($len < $options['minimum']) {
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
# If you have set the max length option
if(isset($options['maximum'])) {
if($len > $options['maximum']) {
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
# If you have set an exact length option
if(isset($options['is'])) {
if($len != $options['is']) {
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes are numbers
* eg. validates_numericality_of('value')
* @param string|array $attribute_names
function validates_numericality_of($attribute_names, $message = null, $only_integer = false, $allow_null = false) {
foreach((array) $attribute_names as $attribute_name) {
$value = $this->$attribute_name;
# Skip validation if you allow null
if($allow_null && is_null($value)) {
if(!is_integer($value)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
if(!is_numeric($value)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes are not blank
* eg. validates_presence_of(array('firstname', 'lastname'))
* @param string|array $attribute_names
function validates_presence_of($attribute_names, $message = null) {
foreach((array) $attribute_names as $attribute_name) {
if($this->$attribute_name === '' || is_null($this->$attribute_name)) {
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Validates that specified attributes are unique in the model database table
* eg. validates_uniqueness_of('username')
* @param string|array $attribute_names
function validates_uniqueness_of($attribute_names, $message = null) {
foreach((array) $attribute_names as $attribute_name) {
# Conditions for new and existing record
$conditions = sprintf("%s = %s", $attribute_name, $quoted_value);
$conditions = sprintf("%s = %s AND %s", $attribute_name,
$attribute_human = Inflector::humanize($attribute_name);
$this->add_error("{ $attribute_human} { $message}", $attribute_name);
* Return the error message for a validation function
private function get_error_message_for_validation($message, $key, $value = null) {
# Return default error message
# Return your custom error message
* Test whether argument is a PEAR Error object or a MDB2 Error object.
* @param object $obj Object to test
* @return boolean Whether object is one of these two errors
function is_error($obj) {
if((PEAR::isError($obj)) || (MDB2::isError($obj))) {
* Throw an exception describing an error in this object
* @throws {@link ActiveRecordError}
function raise($message) {
$error_message .= "Error Message: ". $message;
throw new ActiveRecordError($error_message, "ActiveRecord Error", "500");
* Add or overwrite description of an error to the list of errors
* @param string $error Error message text
* @param string $key Key to associate with the error (in the
* simple case, column name). If omitted, numeric keys will be
* assigned starting with 0. If specified and the key already
* exists in $errors, the old error message will be overwritten
* with the value of $error.
function add_error($error, $key = null) {
* Return description of non-fatal errors
* @param boolean $return_string
* <li>true => Concatenate all error descriptions into a string
* using $seperator between elements and return the
* <li>false => Return the error descriptions as an array</li>
* @param string $seperator String to concatenate between error
* descriptions if $return_string == true
* @return mixed Error description(s), if any
function get_errors($return_string = false, $seperator = "<br>") {
if($return_string && count($this->errors) > 0) {
return implode($seperator, $this->errors);
* Return errors as a string.
* Concatenate all error descriptions into a stringusing
* $seperator between elements and return the string.
* @param string $seperator String to concatenate between error
* @return string Concatenated error description(s), if any
function get_errors_as_string($seperator = "<br>") {
* Log SQL query in development mode
* If running in development mode, log the query to self::$query_log
* @param string SQL to be logged
function log_query($query) {
if(TRAX_ENV == "development" && $query) {
self::$query_log[] = $query;
// -- set Emacs parameters --
// c-hanging-comment-ender-p: nil
|