Abstract Class ActiveRecord_Base

Description

An ActiveRecord implementation for PHP 5.

Designed to eventually offer as much of the functionality available in Ruby on Rails's ActiveRecord implementation as is feasible, this is a base class for building data models capable of storing and retrieving themselves from permanent storage (a database) and whose attributes are largely driven by the database schema as opposed to being defined in the class. That's a long-winded way of saying ActiveRecord is a fast way to create objects that mirror a database table.

Take, for example, a table created with the following SQL:

  1.    CREATE TABLE users (
  2.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  3.      username      VARCHAR(255NOT NULL UNIQUE,
  4.      full_name     VARCHAR(255)     NULL,
  5.      password_hash VARCHAR(255NOT NULL,
  6.      disabled      TINYINT(1)   NOT NULL,
  7.      last_login    DATETIME         NULL
  8.    );

To create an active record class linked to this table, all you need to write is:

  1.    class User extends ActiveRecord_Base {
  2.    }

That's it. Your User class (note User is singular while the table users is plural) now automatically has properties named id, username, full_name, password_hash, disabled, and last_login. It also inherits convenient finder and save methods from the base ActiveRecord class and includes conveniences for easily updating an object with values submitted from a web form.

For those already familiar with the Rails implemenation, it's worth nothing several significant differences between it and this implementation. Most notably, methods wich apply to the table or class as a whole are not implemented as static methods. This is due to a number of limitations in PHP. Specifically, PHP does not provide any visibility about the scope in which it was called to static method. For example, let's say a static method foo is defined on a class A and a class B inherits from class A but does not definie it's own method foo. Within method foo you have no way of knowing whether it was invoked by calling A::foo() or B::foo, and that distinction is critical for any ActiveRecord implementation. For related reasons, it would also not possible for class B to override other static methods defined by A and have A call those methods. That is necessary if derived classes want to provide any class-specific behavior at the class or table level. Finally, PHP does not have facilities for true class-level metadata or behavior (there's no Class class that every object has an instance of, only a class name). At the time this code was being developed, PHP announced the availability of "late static bindings" beginning in version 5.3.0. While that may address some of the issues, it's still somewhat unclear how easy it would be for a base class to understand the calling scope when being called in the context of a derived class, and the desire to support as many 5.x versions of PHP as possible ruled that out as a viable alternative. So, in a nutshell, you'll need an instance of a class before doing any operations at all.

Example:

  1.    $user new User();
  2.    $fred $user->find_first(array('conditions'=>"username='fred'"))// find the record with username fred

The other significant deviation from the approach used by rails is in the area of class initialization. Ruby allows more than just method and property definitions within the body of a class or module. It's possible to invoke methods and they in turn can affect the definition of your class or module. Of course, PHP doesn't have any kind of facility like that, which means we need another way to indicate things like use a different table name or primary key for this class. For this implementation, we introduce a method named init_class which is invoked only once during a script's lifecycle when the class should first be initialized. Other ActiveRecord implementations have used different approaches, including using attributes to indicate this information. We felt this approach provided for the most readable and easily documented code and also gives the most flexibility by allowing the execution of arbitrary code at startup.

For clarification, here's an example of defining a UserProfile class which maps to a table named users (instead of user_profiles, as would otherwise be assumed):

  1.    class UserProfile {
  2.      protected function init_class({
  3.        $this->set_table_name('users');
  4.      }
  5.    }

A more subtle, but important, difference from Rails is the handling of derived classes. Like Rails, this class implements single table inheritance. Let's say we have two classes:

  1.    class User extends ActiveRecord_Base {
  2.    }
  3.  
  4.    class AdminUser extends User {
  5.    }

Here, as in Rails, instances of both classes would be stored on a table named user. Which class each record was an instance of would be distinguished through the use of a type column, which would have the value 'User' for User instances and 'AdminUser' for AdminUser instances. Things get different, however, when additional abstract classes find their way into the mix. Take, for example:

  1.    abstract class MyActiveRecord extends ActiveRecord_Base {
  2.      protected function init_class({
  3.        $this->set_table_name_prefix('myapp_');
  4.      }
  5.    }
  6.  
  7.    class User extends MyActiveRecord {
  8.    }
  9.  
  10.    class AdminUser extends User {
  11.    }

In this case, both User and AdminUser objects would be stored in a table named myapp_users, not myapp_my_active_record. That's because this implementation ignores abstract base classes for the pupose of table naming. As shown here, that can be conveniently used to set policy which is inherited by derived classes. In Ruby this same effect can be achieved by redefining portions of the ActiveRecord::Base class, but, of course, that's much less easily achieved (if at all) in PHP.

The final important convention to note in this class is the naming convention used for mutator and accessor methods. The get method for a property named foo will have the signature foo(). The set method for a property named foo will have the signature set_foo(). This is helpful not only for tracking down the mutators and accessors for your favorite properties, but also for defining custom methods for accessing or setting properties created from database columns. Let's say, for example, I want to always return the last_login property for my User object as an instance of a custom objected named MyDateTime, and likewise I want to always accept an object of the same type when setting the property. I can easily set that up like so:

  1.    class User extends ActiveRecord_Base {
  2.      public function last_login({
  3.        return new MyDateTime($this->read_attribute('last_login'));
  4.      }
  5.  
  6.      public function set_last_login($myDateTimeObj{
  7.        $this->write_attribute('last_login'$myDateTimeObj->to_db_value());
  8.      }
  9.    }

Note the use of the read_attribute and write_attribute methods here to gain access to the underlying object properties. Even though only these two methods have been declared, they will also be used anytime the corresponding public properties are accessed. Take for example these lines of code:

  1.    $oldLoginTime $user->last_login;
  2.    $user->last_login new MyDateTime('2007-04-01 0:00:00');

The first line will actually invoke the last_login() method, and the second will invoke the set_last_login() method. That's because the base ActiveRecord class actually maps all access to non-existent properties to the corresponding accessor or mutator method. The byproduct of this behavior is that many of the methods defined on the ActiveRecord class can also be accessed as though they were public properties.

Events

ActiveRecord supports the following event lifecycle:

  • (.) save
  • (.) is_valid
  • (1) before_validation
  • (2) before_validation_on_create / before_validation_on_update
  • (.) validate
  • (.) validate_on_create / validate_on_update
  • (3) after_validation
  • (4) after_validation_on_create / after_validation_on_update
  • (5) before_save
  • (6) before_create / before_update
  • (.) create_record / update_record
  • (7) after_create / after_update
  • (8) after_save
And:

  • (1) before_destroy
  • (.) destroy
  • (2) after_destroy
Listeners may be added for any of the above fourteen events using a java-like add_event_listener method or using the convenience methods of the same name.

Example:

  1.    class User extends ActiveRecord_Base {
  2.      protected function custom_hook({
  3.        // do some custom work before validation
  4.      }
  5.  
  6.      protected function init_class({
  7.        $this->before_validation('custom_hook');
  8.  
  9.        // nearly equivalent to:
  10.        $this->add_event_listener('before_validation'array($this'custom_hook'));
  11.      }
  12.    }

  • abstract:

Located in /activerecord/lib/ActiveRecord/Base.php (line 476)


	
			
Direct descendents
Class Description
 class Migration_Record
Variable Summary
 mixed $attributes
 mixed $errors
 mixed $logger
 mixed $metaInf
 mixed $new_record
 mixed $readonly
Method Summary
 ActiveRecord_Base __construct ([array $attrs = false])
 void add_conditions (string &$sql, array $options)
 void add_event_listener (string $eventName, callback $function)
 void add_joins (string &$sql, array $options)
 void add_limit (string &$sql, array $options)
 void add_method_proxy (string $name, callback $callback)
 void add_order (string &$sql, array $options)
 void after_create (string $name)
 void after_destroy (string $name)
 void after_save (string $name)
 void after_update (string $name)
 void after_validation (string $name)
 void after_validation_on_create (string $name)
 void after_validation_on_update (string $name)
 array assemble_finder_options (array $attrs, array $options)
 array attributes ()
 string attributes_for_set ()
 array attribute_names ()
 bool attribute_present (string $attribute)
 void attr_accessible ()
 void attr_protected ()
 void base_class_name ()
 void before_create (string $name)
 void before_destroy (string $name)
 void before_save (string $name)
 void before_update (string $name)
 void before_validation (string $name)
 void before_validation_on_create (string $name)
 void before_validation_on_update (string $name)
 void belongs_to ( $association_name, [array $options = array()], string $assocation_name)
 string class_name ([string $name = NULL])
 array columns ()
 string columns_for_insert ()
 array columns_hash ()
 array column_names ()
 PDO connection ()
 array content_columns ()
 int count ([ $options = array()], string $sql)
 int count_by_sql (string $sql)
 object create ([array $attrs = false])
 array create_finder_attribute_hash (string $attributeNames, array $args, array &$options)
 object create_or_fail ([array $attrs = false])
 bool create_record ()
 ActiveRecord_Base decrement (string $attribute)
 bool decrement_and_save (string $attribute)
 int decrement_counter (string $counterName, string $id)
 int delete ()
 int delete_all ([mixed $conditions = false])
 void delete_cached_attribute (string $name)
 void destroy ()
 void destroy_all ([mixed $conditions = false])
 bool exists (mixed $test)
 mixed find ()
 array find_all ([array $options = array()])
 array find_by_sql (string $sql)
 mixed find_first ([array $options = array()])
 void fire_event (string $eventName)
 bool has_attribute (string $attrName)
 boolean has_cached_attribute (string $name)
 void has_many ( $association_name, [array $options = array()], string $assocation_name)
 void has_one ( $association_name, [array $options = array()], string $assocation_name)
 mixed id ()
 ActiveRecord_Base increment (string $attribute)
 bool increment_and_save (string $attribute)
 int increment_counter (string $counterName, string $id)
 string inheritance_column ()
 void init_class ()
 object instantiate (array $record)
 bool is_valid ()
 Logger logger ()
 object model (string $className)
 bool new_record ()
 string primary_key ()
 void process_includes (mixed $includes, array &$records)
 bool readonly ()
 mixed read_attribute (string $name)
 mixed read_attribute_before_type_cast (string $name)
 mixed read_cached_attribute (string $name)
 bool remove_event_listener (string $eventName, callback $function)
 void reverse_type_cast (mixed $value, ActiveRecordColumn $col)
 void run_validations (int $type)
 bool save ([bool $validate = true])
 void save_or_fail ()
 void send_parent (string $method, [array $args = NULL], [mixed $default = NULL])
 string sequence_name ()
 void set_attributes (array $attrs)
 void set_connection (PDO $conn)
 void set_id (mixed $value)
 void set_inheritance_column (string $name)
 void set_primary_key (string $name)
 void set_readonly (bool $flag)
 void set_sequence_name (string $name)
 void set_table_name (string $name)
 string set_table_name_prefix (string $prefix)
 string set_table_name_suffix (string $suffix)
 bool table_exists ()
 string table_name ()
 string table_name_prefix ()
 string table_name_suffix ()
 ActiveRecord_Base toggle (string $attribute)
 bool toggle_and_save (string $attribute)
 void type_cast (mixed $value, ActiveRecordColumn $col)
 string type_condition ()
 mixed update (mixed $id, array $attrs)
 int update_all (string $updates, [mixed $conditions = false])
 bool update_attribute (string $name, mixed $value)
 bool update_attributes (array $attributes)
 void update_attributes_or_fail (array $attributes)
 bool update_record ()
 void validate ()
 void validates_confirmation_of (mixed $attributes, [array $options = array()])
 void validates_exclusion_of (mixed $attributes, array $invalidValues, [array $options = array()])
 void validates_format_of (mixed $attributes, string $pattern, [array $options = array()])
 void validates_inclusion_of (mixed $attributes, array $validValues, [array $options = array()])
 void validates_length_of (mixed $attributes, [array $options = array()])
 void validates_numericality_of (mixed $attributes, [array $options = array()])
 void validates_presence_of (mixed $attributes, [array $options = array()])
 void validates_uniqueness_of (mixed $attributes, [array $options = array()])
 void validate_find_options ( $options)
 void validate_options ( &$options,  &$allowed)
 int validation_name_to_type (string $name)
 string values_for_insert ()
 void write_attribute (string $name, mixed $value)
 void write_cached_attribute (string $name, mixed $value)
 mixed __call (string $name, array $args)
 mixed __get (string $name)
 bool __isset (string $name)
 void __set (string $name, mixed $value)
 void __sleep ()
 void __unset (string $name)
Variables
mixed $attributes (line 493)

Attributes

  • access: protected
mixed $cached_attributes (line 509)

A collection of cached attribute values

  • access: protected
mixed $errors (line 505)

Any errors that apply to this object

  • access: protected
mixed $logger (line 489)

Cached logger

  • access: protected
mixed $metaInf (line 485)

Class meta information

  • access: protected
mixed $new_record (line 497)

Indicates whether this is a new record or not

  • access: protected
mixed $readonly (line 501)

Indicates whether this record is read-only or not

  • access: protected
Methods
Constructor __construct (line 2187)

Constructor

Accepts an optional associative array of attribute names and values as the initial values to set on the object.

Note that although this behavior is not very clearly explained in the PHP documentation, if derived classes do not specify a constructor, they will inherit this one by default.

  • access: public
ActiveRecord_Base __construct ([array $attrs = false])
  • array $attrs: Any initial attributes to use
accessible_attributes (line 1357)

Return a list of all attributes which have been made accessible to mass assignment by passing them to attr_accessible (the list is always maintained in sorted order).

  • access: public
array accessible_attributes ()
add_conditions (line 2880)

Add conditions fragment to a SQL statement

  • access: protected
void add_conditions (string &$sql, array $options)
  • string &$sql: The SQL statement being constructed (reference)
  • array $options: The array of options provided
add_event_listener (line 1438)

Add an event listener to this class.

  • access: public
void add_event_listener (string $eventName, callback $function)
  • string $eventName: Name of the event to bind the listener to
  • callback $function: Modified PHP style callback: a function name, an array containing an object an a method name on that object, or an array containing NULL and a method name on this class meaning to always invoke the method for the current instance.
add_joins (line 2869)

Add join fragment to a SQL statement

  • access: protected
void add_joins (string &$sql, array $options)
  • string &$sql: The SQL statement being constructed (reference)
  • array $options: The array of options provided
add_limit (line 2957)

Add limit information to the SQL statement

  • access: protected
void add_limit (string &$sql, array $options)
  • string &$sql: The SQL statement being constructed (reference)
  • array $options: The array of options provided
add_method_proxy (line 3234)

Define a proxy for a method name.

A proxied method allows the addition of "virtual" methods to a class which are actually invoked on another object. This is useful for features such as associations which need to define additional methods dynamically.

Methods calls made to the other object include two additional parameters which are always the first two parameters passed. They are the ActiveRecord_Base instance the call is being invoked on and an ActiveRecord_Proxy object which allows direct access to the attributes for the object.

Example:

  1.    class MyProxy {
  2.      public function full_name($record$proxy{
  3.        return implode(' 'array($record->first_name$record->last_name));
  4.      }
  5.    }
  6.  
  7.    class Student extends ActiveRecord_Base {
  8.      protected function init_class({
  9.        $this->add_method_proxy('full_name'array(new MyProxy()'full_name'));
  10.      }
  11.    }
  12.  
  13.    $student new Student();
  14.    $student->full_name// calls full_name method on MyProxy

  • access: protected
void add_method_proxy (string $name, callback $callback)
  • string $name: The name of the method to proxy
  • callback $callback: The callback to invoke for the method
add_order (line 2897)

Add order by fragment to a SQL statement

  • access: protected
void add_order (string &$sql, array $options)
  • string &$sql: The SQL statement being constructed (reference)
  • array $options: The array of options provided
after_create (line 1505)

Register a method on this class to be called after a save operation is performed for a new record.

  • access: public
void after_create (string $name)
  • string $name: The name of the method to register.
after_destroy (line 1608)

Register a method on this class to be called after the record is destroyed.

  • access: public
void after_destroy (string $name)
  • string $name: The name of the method to register.
after_save (line 1526)

Register a method on this class to be called after any save operation is performed.

  • access: public
void after_save (string $name)
  • string $name: The name of the method to register.
after_update (line 1516)

Register a method on this class to be called after a save operation is performed for a record being updated (non-new record).

  • access: public
void after_update (string $name)
  • string $name: The name of the method to register.
after_validation (line 1588)

Register a method on this class to be called after any validation operation is performed.

  • access: public
void after_validation (string $name)
  • string $name: The name of the method to register.
after_validation_on_create (line 1567)

Register a method on this class to be called after a validation operation is performed for a new record.

  • access: public
void after_validation_on_create (string $name)
  • string $name: The name of the method to register.
after_validation_on_update (line 1578)

Register a method on this class to be called after a validation operation is performed for a record being updated (non-new record).

  • access: public
void after_validation_on_update (string $name)
  • string $name: The name of the method to register.
assemble_finder_options (line 3163)

Create an options parameter for passing to a find_* method using the output from create_finder_attribute_hash

  • access: protected
array assemble_finder_options (array $attrs, array $options)
  • array $attrs: The hash returned by create_finder_attribute_hash
  • array $options: Any additional options to include
attributes (line 2218)

Returns this object's attributes as an associative array.

  • access: public
array attributes ()
attributes_for_set (line 3472)

Return the list of column names and attribute values for use in the SET clause of an UPDATE statement. The primary key column is excluded.

  • access: protected
string attributes_for_set ()
attributes_from_column_definition (line 2989)

Return an associative array of attributes representing the default values for the fields on this class's table. The array keys are the field names and the values are the default values.

  • access: protected
array attributes_from_column_definition ()
attributes_protected_by_default (line 3093)

Return a list of attributes which are never permitted in mass-assignment. The returned list must be sorted. By default, the returned list include the primary key and inheritance column.

  • access: protected
array attributes_protected_by_default ()
attribute_names (line 2711)

Returns an array of names for the attributes available on this object. The returned list is sorted alphabetically.

  • access: public
array attribute_names ()
attribute_present (line 2684)

Returns true if the named attribute exists for this object and has a non-empty value (not null, false, 0, the empty string, or any empty array).

  • access: public
bool attribute_present (string $attribute)
  • string $attribute: The name of the attribute to check
attr_accessible (line 1334)

Accepts the names of one or more attributes which are allowed to

be assigned through mass assignment in this class (assignment through the constructor, create method, set_attributes method, etc.). If this method is used, only those attributes specified as accessible are allowed to be assigned through mass assignment.

  • access: public
void attr_accessible ()
attr_protected (line 1291)

Accepts the names of one or more attributes which are protected from mass assignment in this class (assignment through the constructor, create method, set_attributes method, etc.).

  • access: public
void attr_protected ()
base_class_name (line 3055)

Traverses the list of this class's parents to return the oldest ancestor which is not abstract (this is for single table inheritance since inherited classes uses the base class's table.

  • access: protected
void base_class_name ()
before_create (line 1484)

Register a method on this class to be called before a save operation is performed for a new record.

  • access: public
void before_create (string $name)
  • string $name: The name of the method to register.
before_destroy (line 1598)

Register a method on this class to be called before the record is destroyed.

  • access: public
void before_destroy (string $name)
  • string $name: The name of the method to register.
before_save (line 1474)

Register a method on this class to be called before any save operation is performed.

  • access: public
void before_save (string $name)
  • string $name: The name of the method to register.
before_update (line 1495)

Register a method on this class to be called before a save operation is performed for a record being updated (non-new record).

  • access: public
void before_update (string $name)
  • string $name: The name of the method to register.
before_validation (line 1536)

Register a method on this class to be called before any validation operation is performed.

  • access: public
void before_validation (string $name)
  • string $name: The name of the method to register.
before_validation_on_create (line 1546)

Register a method on this class to be called before a validation operation is performed for a new record.

  • access: public
void before_validation_on_create (string $name)
  • string $name: The name of the method to register.
before_validation_on_update (line 1557)

Register a method on this class to be called before a validation operation is performed for a record being updated (non-new record).

  • access: public
void before_validation_on_update (string $name)
  • string $name: The name of the method to register.
belongs_to (line 1972)

Specifies a one to one association with another class where the foreign key resides in this class.

For example:

  1.    class Book extends ActiveRecord_Base {
  2.      public function init_class({
  3.        $this->belongs_to('author');
  4.      }
  5.    }
  6.  
  7.    class Author extends ActiveRecord_Base {
  8.    }

Implies a table structure like:

  1.    CREATE TABLE books (
  2.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  3.      author_id     INTEGER          NULL,
  4.      ...
  5.    );
  6.  
  7.    CREATE TABLE authors (
  8.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  9.      ...
  10.    );

A belongs_to association adds four methods to the class:

  • association($force_reload = false): Return the associated object
  • set_association($value): Set the associated object
  • build_assocation($attributes = array()): Create a new associated object from a set of attriubtes
  • create_association($attributes = array()): Create and save a new associated object from a set of attributes
Options for the association are:
  • class_name: Set the name of the associated class, the default is inferred from the association name ('user' is assumed to come from a class named 'User').
  • foreign_key: Set the foreign key name, the default is to append _id to the association name.
  • validate_key: Whether or not to add a validation for the foreign key field, the default is to add one (true).
Note that assigning an object via the set_association method will not automatically cause it to be saved, nor will modifications to it be saved automatically when this object is saved. It must be explicitly saved on its own. The only exception to this is for newly created records. If you assign a newly created (unsaved) associate object using this object's set_association method, the associate object will be saved when you save this object, since that is required in order to correctly populate the foreign key.

  • access: public
void belongs_to ( $association_name, [array $options = array()], string $assocation_name)
  • string $assocation_name: The name of the association
  • array $options: Any options for the assocation
  • $association_name
class_name (line 1405)

Turn a table name back into a class name. This follows the reverse rules of the table_name method. So, for example, "my_objects" becomes "MyObject".

  • access: public
string class_name ([string $name = NULL])
  • string $name: The table name to convert (defaults to this class's table).

Redefined in descendants as:
columns (line 1206)

Return an array of ActiveRecord_Column objects for the table associated with this class.

  • access: public
array columns ()
columns_for_insert (line 3489)

Return the list of all attribute names prepared for use in an insert statement

  • access: protected
string columns_for_insert ()
columns_hash (line 1226)

Returns an associative array of column objects keyed by column name for the table associated with this class.

  • access: public
array columns_hash ()
column_for_attribute (line 1281)

Returns the column object for the named attribute

  • access: public
ActiveRecord_Column column_for_attribute (string $name)
  • string $name: The attribute name
column_names (line 1241)

Returns an array of column names as strings.

  • access: public
array column_names ()
connection (line 1072)

Return the database connection for this class

  • access: public
PDO connection ()
content_columns (line 1260)

Returns an array of column objects suitable for direct editing

by a user. The primary key; the inheritance column; all columns ending in _id or _count; and any columns named created_at, created_on, updated_at, updated_on, or lock version are omitted from the returned list.

  • access: public
array content_columns ()
count (line 959)

Returns a count of records matching the provided criteria.

Accepted options are the same as for find_all().

Example

  1.    $person new Person();
  2.    $person->count(array('conditions'=>"last_name='Smith'"));

  • access: public
int count ([ $options = array()], string $sql)
  • string $sql: The complete SQL statement to run
  • $options
count_by_sql (line 985)

Returns the result of an SQL statement that should only include a COUNT(*) -- or equivalent -- in the SELECT clause.

Example

  1.    $person new Person();
  2.    $person->count_by_sql("SELECT COUNT(*) FROM people WHERE last_name='Smith'");

  • access: public
int count_by_sql (string $sql)
  • string $sql: The complete SQL statement to run
create (line 742)

Create and save (validation permitting) an object. The newly created object is returned. If validation fails, the unsaved object is still returned.

Example:

  1.    $student new Student();
  2.  
  3.    $emptyStudent $student->create();
  4.  
  5.    $sallyMae $student->create(array('first_name' => 'Sally Mae',
  6.                                       'last_name'  => 'Jones',
  7.                                       'ssn'        => '123-45-6789',
  8.                                       'gpa'        => 3.9));

  • access: public
object create ([array $attrs = false])
  • array $attrs: Optional associative array of attributes for the new object.
create_finder_attribute_hash (line 3133)

Extract attribute names from an "_and_" separated string and construct an associative array using a corresponding array of arguments.

  • return: A hash with attribute names as keys and the corresponding values taken from $args
  • access: protected
array create_finder_attribute_hash (string $attributeNames, array $args, array &$options)
  • string $attributeNames: The string of attribute names
  • array $args: The corresponding argument list
  • array &$options: Output parameter for any additional options argument in $args
create_or_fail (line 758)

Like create, but calls save_or_fail, so if validation fails, an exception is thrown.

  • access: public
object create_or_fail ([array $attrs = false])
  • array $attrs: Optional associative array of attributes for the new object.
create_or_update (line 3376)

Handles performing the correct save operation for the object.

  • return: Success or failure indicator
  • access: protected
bool create_or_update ()
create_record (line 3435)

Create a new record in the database for this object

  • return: Success or failure indicator
  • access: protected
bool create_record ()
decrement (line 2623)

Subtracts one from the value of the named attribute. If the attribute is null, it is first initialized to zero before subtracting one.

  • return: A reference to self
  • access: public
ActiveRecord_Base decrement (string $attribute)
  • string $attribute: The name of the attribute to decrement
decrement_and_save (line 2636)

Decrements the named attribute and saves the object.

  • return: The success or failure indicator from the save operation
  • access: public
bool decrement_and_save (string $attribute)
  • string $attribute: The name of the attribute to decrement
decrement_counter (line 1037)

Similar to increment_counter, but decrements the specified counter instead.

This example decrements the in_stock field for the Product with id 204:

  1.    $product new Product();
  2.    $product->decrement_counter('in_stock'204);

  • return: The number of records updated (0 or 1)
  • access: public
int decrement_counter (string $counterName, string $id)
  • string $counterName: The name of the counter to decrement
  • string $id: The id of the record to decrement it for
delete (line 816)

Deletes the record with the given id (or records with the given

ids). The record is not instantiated first, so no callbacks are triggered. As with find, this method accepts one or more arguments. Any arrays which are passed are assumed to be an array of ids.

  • return: The count of deleted objects.
  • access: public
int delete ()
delete_all (line 923)

Destroys all records that match the given conditions. The

records are not instantiated first, and, as such, no callbacks are triggered. As with the conditions option for a find* method, the conditions argument is a SQL fragment suitable for use in a where clause. The conditions parameter may be a string or an array with the first elementing containing the SQL fragment and the remaining containing parameters.

Returns a count of records that were deleted.

Examples:

  1.   $article new Article();
  2.   $article->delete_all("archived=1 AND archived_on<='2000-01-01'");
  3.   $article->delete_all(array("archived=1 AND archived_on<=?"$exipireDate));

  • access: public
int delete_all ([mixed $conditions = false])
  • mixed $conditions: Any conditions
delete_cached_attribute (line 3366)

delete_cached_attribute removes a temporary value previously set with write_cached_attribute

  • access: protected
void delete_cached_attribute (string $name)
  • string $name: The attribute name
destroy (line 2522)

Delete the record from the database

  • access: public
void destroy ()
destroy_all (line 893)

Destroys the objects for a set of records that match the given

conditions. As with the conditions option for a find* method, the conditions argument is a SQL fragment suitable for use in a where clause. The conditions parameter may be a string or an array with the first elementing containing the SQL fragment and the remaining containing parameters.

Examples:

  1.   $article new Article();
  2.   $article->destroy_all("archived=1 AND archived_on<='2000-01-01'");
  3.   $article->destroy_all(array("archived=1 AND archived_on<=?"$exipireDate));

  • access: public
void destroy_all ([mixed $conditions = false])
  • mixed $conditions: Any conditions
ensure_proper_type (line 3003)

Sets the inheritance column value for this object if needed.

  • access: protected
void ensure_proper_type ()
errors (line 2740)

Return the errors collection for this object

  • access: public
exists (line 711)

Accepts an id or set of conditions and returns true if a

matching record exists, otherwise it returns false. If the test parameter is an array, it is assumed to contain conditions in the same format used with the 'conditions' option for find. Anything else is assumed to be an id.

Example:

  1.    $student new Student();
  2.  
  3.    if ($student->exists(25)) /* student with id 25 exists */ }
  4.    if ($student->exists(array('last_name=?''Smith')) /* there is a student Smith */ }

  • access: public
bool exists (mixed $test)
  • mixed $test: The id or conditions to test for
find (line 540)

Find one or more records with the specified id(s). This function accepts one or more ids as it's argument. If an array is passed, it is assumed to be a list of ids.

Returns the record or records with the given ids. In the case of a single id, a single object is returned. In the case of multiple ids, an array of objects is returned. The count of objects found must match the count of ids or an exception is thrown.

Example:

  1.    $student      new Student();
  2.    $oneStudent   $student->find(5);
  3.    $studentArray $student->find(53047);

  • return: The object or list of objects.
  • access: public
mixed find ()
find_all (line 628)

Retrieve all records matching the provided criteria.

Options are:

  • conditions: A SQL fragment for use in the WHERE clause. For example, "archived=1" or array("username=?", $username).
  • order: A SQL fragment for use in the ORDER BY clause such as "name, created_at DESC".
  • limit: An integer limiting the number of rows to return.
  • offset: An integer specifying the offset from which fetching begins (1 indicates the first row).
  • joins: A SQL fragment to specify additional joins needed for the conditions.
  • from: The table or view name to select from. The default name is provided by the table_name method, but this allows a temporary override.
  • readonly: Return the records as read-only
  • include: The name of an association or an array of association names to eagerly load with the records.
Returns an array containing all matching records found. If no matches are found, an empty array is returned.

Example:

  1.    $student   new Student();
  2.    $deansList $student->find_all('conditions'=>'gpa >= 3.8');

  • return: The list of objects found
  • access: public
array find_all ([array $options = array()])
  • array $options: An associative array of options. Possible keys are explained above.
find_by_sql (line 666)

Retrieve records by a raw SQL statement instead of through the normal find helper methods.

Returns an array containing all matching records found. If no matches are found, an empty array is returned.

Example:

  1.    $student new Student();
  2.    $smiths  $student->find_by_sql("SELECT * from students WHERE last_name='Smith'");

  • return: The list of object found
  • access: public
array find_by_sql (string $sql)
  • string $sql: The complete SQL statement to run
find_first (line 592)

Retrieve the first record matching the provided criteria.

Options are:

  • conditions: A SQL fragment for use in the WHERE clause. For example, "archived=1" or array("username=?", $username).
  • order: A SQL fragment for use in the ORDER BY clause such as "name, created_at DESC".
  • limit: An integer limiting the number of rows to return.
  • offset: An integer specifying the offset from which fetching begins (1 indicates the first row).
  • joins: A SQL fragment to specify additional joins needed for the conditions.
  • from: The table or view name to select from. The default name is provided by the table_name method, but this allows a temporary override.
  • readonly: Return the records as read-only
  • include: The name of an association or an array of association names to eagerly load with the record.
Returns the first object matching the criteria. If not matches are found, returns NULL.

Example:

  1.    $student    new Student();
  2.    $firstSally $student->find_first('conditions'=>"first_name='Sally'");
  3.    $bySSN      $student->find_first('conditions'=>array('ssn=?'$ssn));
  4.    $topRanked  $student->find_first('order'=>'gpa DESC');

  • return: The first object found or NULL
  • access: public
mixed find_first ([array $options = array()])
  • array $options: An associative array of options. Possible keys are explained above.
fire_event (line 3513)

Notifies any registered event listeners

  • access: protected
void fire_event (string $eventName)
  • string $eventName: The event name to notify listeners for
get_meta_info (line 2828)

Called internally to access the class-level meta information

  • access: protected
ActiveRecord_MetaInfo get_meta_info ()
has_attribute (line 2701)

Returns true if this object has the named attribute (even if it is empty)

  • access: public
bool has_attribute (string $attrName)
  • string $attrName: The name of the attribute to check
has_cached_attribute (line 3320)

Returns true if this object has a cached attribute with the provided name. See write_cached_attribute for more information on cached attributes.

  • access: protected
boolean has_cached_attribute (string $name)
  • string $name: The attribute name
has_many (line 2127)

Specifies a one to many association with another class where the foreign key resides in the other class.

For example:

  1.    class Menu extends ActiveRecord_Base {
  2.      public function init_class({
  3.        $this->has_many('menu_items');
  4.      }
  5.    }
  6.  
  7.    class MenuItem extends ActiveRecord_Base {
  8.    }

Implies a table structure like:

  1.    CREATE TABLE menus (
  2.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  3.      ...
  4.    );
  5.  
  6.    CREATE TABLE menu_items (
  7.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  8.      menu_id       INTEGER          NULL,
  9.      ...
  10.    );

A has_many association adds four methods to the class:

  • association($force_reload = false): Return the associated objects as a collection
  • set_association($collection): Set the collection of associated objects (takes an array as the argument)
  • association_singular_ids: Return an array of the associated object ids
  • set_association_singular_ids($ids): Set the collection of associated objects by list of ids (takes an array of ids as the argument)
The association() method returns an instance of ActiveRecord_Association_Collection which also offers the following methods:
  • association[] (array-based access and operations)
  • association->build($attributes)
  • association->clear()
  • association->count()
  • association->create($attributes)
  • association->delete($associate)
  • association->exists($options)
  • association->find($id[, $id, ...])
  • association->find_all($options)
  • association->find_first($options)
  • association->is_empty()
  • association->length()
  • association->size()
Options for the association are:
  • class_name: Set the name of the associated class, the default is inferred from the association name ('users' is assumed to come from a class named 'User').
  • foreign_key: Set the foreign key name, the default is to append _id to the associated class name.
  • primary_key: The name of the key field on this class, defaults to id() (whatever the table primary key is set to).
  • order: Ordering to return the associated objects in (similar to order option for find_all).
Note that either adding an object to or or removing an object from the collection will cause the object to be saved with an updated foreign key value. Special cases exist for both newly created associate objects and adding associates to a newly created instance of this class. If you add an unsaved object to this class, it will only be saved if you call the save method on this class. Similarly, if you add another object to this class before saving this class, the primary key value is not yet known, and so the associated object will not be saved until you save the instance of this class.

  • access: public
void has_many ( $association_name, [array $options = array()], string $assocation_name)
  • string $assocation_name: The name of the association
  • array $options: Any options for the assocation
  • $association_name
has_one (line 2042)

Specifies a one to one association with another class where the foreign key resides in the other class.

For example:

  1.    class Book extends ActiveRecord_Base {
  2.    }
  3.  
  4.    class Author extends ActiveRecord_Base {
  5.      public function init_class({
  6.        $this->has_one('book');
  7.      }
  8.    }

Implies a table structure like:

  1.    CREATE TABLE books (
  2.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  3.      author_id     INTEGER          NULL,
  4.      ...
  5.    );
  6.  
  7.    CREATE TABLE authors (
  8.      id            INTEGER      NOT NULL PRIMARY_KEY AUTOINCREMENT,
  9.      ...
  10.    );

A has_one association adds four methods to the class:

  • association($force_reload = false): Return the associated object
  • set_association($value): Set the associated object
  • build_assocation($attributes = array()): Create a new associated object from a set of attriubtes
  • create_association($attributes = array()): Create and save a new associated object from a set of attributes
Options for the association are:
  • class_name: Set the name of the associated class, the default is inferred from the association name ('user' is assumed to come from a class named 'User').
  • foreign_key: Set the foreign key name, the default is to append _id to the association name.
  • primary_key: The name of the key field on this class, defaults to id() (whatever the table primary key is set to).
Note that assigning an object via the set_association method will both cause it to be saved with the new foreign key value and will cause any previously associated object to be saved with a null value for its foreign key (effectively unassigns it). Special cases exist for both newly created associate objects and when assigning associates to a newly created instance of this class. If you assign an unsaved object to this class using the set_association method, it will only be saved if you call the save method on this class. Similarly, if you assign another object to this class before saving this class, the primary key value is not yet known, and so the associated object will not be saved until you save the instance of this class.

  • access: public
void has_one ( $association_name, [array $options = array()], string $assocation_name)
  • string $assocation_name: The name of the association
  • array $options: Any options for the assocation
  • $association_name
id (line 2457)

The id method/property always accesses the primary key column, even if the primary key is named something else.

  • access: public
mixed id ()
id_before_type_cast (line 2466)

Access the value of the primary key column before the type cast

  • access: public
mixed id_before_type_cast ()
increment (line 2597)

Adds one to the value of the named attribute. If the attribute is null, it is first initialized to zero before adding one.

  • return: A reference to self
  • access: public
ActiveRecord_Base increment (string $attribute)
  • string $attribute: The name of the attribute to increment
increment_and_save (line 2610)

Increments the named attribute and saves the object.

  • return: The success or failure indicator from the save operation
  • access: public
bool increment_and_save (string $attribute)
  • string $attribute: The name of the attribute to increment
increment_counter (line 1019)

Increments the specified counter for the given id by one.

This example increments the hits field for the Document with id 204:

  1.    $doc new Document();
  2.    $doc->increment_counter('hits'204);

  • return: The number of records updated (0 or 1)
  • access: public
int increment_counter (string $counterName, string $id)
  • string $counterName: The name of the counter to increment
  • string $id: The id of the record to increment it for
inheritance_column (line 1183)

Return the name of the column used for single table inheritance.

  • access: public
string inheritance_column ()
init_class (line 2809)

Called to initialize class-specific information such as associations, validations, etc. Derived classes should implement this method to specify these class-specific details.

  • access: protected
void init_class ()

Redefined in descendants as:
instantiate (line 2843)

Create a new instance of an object from a record. This handles single table inheritance, allowing different types of objects to be instantiated from the same table.

  • access: protected
object instantiate (array $record)
  • array $record: An associative array of the record's values.
is_first_concrete_descendent (line 2924)

Determine if this class is the first concrete descendent from ActiveRecord_Base.

  • access: protected
bool is_first_concrete_descendent ()
is_valid (line 2751)

Determine if this record is valid

  • access: public
bool is_valid ()
load_meta_info (line 1047)

This is invoked automatically by ActiveRecord_InfoMgr when the class-level meta information should be loaded.

  • access: public
ActiveRecord_MetaInfo load_meta_info ()
logger (line 2817)

Return this class's logger

  • access: protected
Logger logger ()
model (line 2160)

A convenience method that calls Support_Util::model()

This method exists purely for more concise code creation. All three of the examples below perform the same operation:

  1.    // write this:
  2.    $post $this->model('BlogPost')->find($id);
  3.  
  4.    // instead of:
  5.    $post Support_Util::model('BlogPost')->find($id);
  6.  
  7.    // or
  8.    $BlogPost new BlogPost();
  9.    $post $BlogPost->find($id);

  • access: public
object model (string $className)
  • string $className: The name of the model class to return
new_record (line 2486)

Returns true if a corresponding record does not yet exist for this object in the database (a new object which has not yet been saved).

  • access: public
bool new_record ()
primary_key (line 1105)

Return the name of this class's primary key. Default is 'id'.

  • access: public
string primary_key ()
process_includes (line 2908)

Handle include processing for a result set

  • access: protected
void process_includes (mixed $includes, array &$records)
  • mixed $includes: The name (or array of names) to include
  • array &$records: The record set to perform the include for
protected_attributes (line 1313)

Return a list of all attributes which have been protected from mass assignment (the list is always maintained in sorted order).

  • access: public
array protected_attributes ()
proxy (line 2782)

Return a proxy object for this class.

Proxies are used by external classes which dynamically extend the functionality of an ActiveRecord class.

  • access: public
proxy_method_for (line 3184)

Return the proxy method for a given method name, or null if none declared.

  • access: protected
ActiveRecord_ProxyMethod proxy_method_for (string $name)
  • string $name: The method to search for
readonly (line 2722)

Returns the setting of the read-only flag for this object

  • access: public
bool readonly ()
read_attribute (line 3281)

Returns the value of an attribute type cast to the correct data type.

  • access: protected
mixed read_attribute (string $name)
  • string $name: The attribute name
read_attribute_before_type_cast (line 3294)

Returns the value of an attribute without performing any type casting.

  • access: protected
mixed read_attribute_before_type_cast (string $name)
  • string $name: The attribute name
read_cached_attribute (line 3334)

Return the value stored in the attribute cache for the given name.

If no value is in the cache, returns null. Note that a null value does not indicate the attribute has no value, only that no cached value is present. See write_cached_attribute for more information on cached attributes.

  • access: protected
mixed read_cached_attribute (string $name)
  • string $name: The attribute name
reload (line 2669)

Reloads the attributes for this object from the database.

  • return: A reference to self
  • access: public
ActiveRecord_Base reload ()
remove_attributes_protected_from_mass_assignment (line 3107)

Remove attributes protected from mass assignment from an associative array

  • access: protected
void remove_attributes_protected_from_mass_assignment (array $attrs)
  • array $attrs: The array to clean
remove_event_listener (line 1454)

Remove an event listener from this class.

  • return: Returns true if the listener was found and removed
  • access: public
bool remove_event_listener (string $eventName, callback $function)
  • string $eventName: Name of the event the listener is bound to
  • callback $function: The callback currently bound
reverse_type_cast (line 3046)

Type cast a value from PHP code into a value suitable for use in

SQL. By default, this method just delegates to the column definition, but, like type_cast, it exists as a hook for derived classes to be able to extend the column definition's behavior on an application-wide basis. For example, if you have a different class you use to represent dates, or another data type for enums in MySQL. Note that this is not the correct place to handle field-specific type casts for an individual field (for example, if the 'foo' field for class 'Bar' is stored as a string but has a wrapper class that is used in PHP code). Overrides for individual fields are best handled by defining accessor and mutator (get/set) methods for those fields.

  • access: protected
void reverse_type_cast (mixed $value, ActiveRecordColumn $col)
  • mixed $value: The value to cast
  • ActiveRecordColumn $col: The column definition (if any) for the value
run_validations (line 3538)

Evaluate all validations of a given type associated with this object

  • access: protected
void run_validations (int $type)
  • int $type: Validation type, as defined by ActiveRecordValidation
save (line 2499)

Save the object to the database. If no record yet exists for the object, a new one is created. Otherwise, the existing record is updated.

  • return: True on success, false on failure
  • access: public
bool save ([bool $validate = true])
  • bool $validate: Performs validations when true, otherwise skips them
save_or_fail (line 2511)

Saves the object to the database. If the save operation does not succeed, a RecordNotSaved exception is thrown.

  • access: public
void save_or_fail ()
send_parent (line 3074)

Invoke a named method on an blank instance of our parent class if our parent is not abstract.

  • access: protected
void send_parent (string $method, [array $args = NULL], [mixed $default = NULL])
  • string $method: The name of the method to invoke
  • array $args: The arguments to pass
  • mixed $default: The default value to return if the parent class is abstract.
sequence_name (line 1388)

Return the name of this class's sequence. This function may be overridden by derived classes. The default name is actually determined by providing the table name and primary key name to the connection. It then builds an appropriate sequence name.

  • access: public
string sequence_name ()
set_attributes (line 2203)

Allows setting of multiple attributes at once by passing an associative array. The array keys are the attribute names and the array values are the values to assign.

  • access: public
void set_attributes (array $attrs)
  • array $attrs: The attributes to assign.
set_connection (line 1087)

Sets the database connection for this class

  • access: public
void set_connection (PDO $conn)
  • PDO $conn: The connection to use
set_id (line 2475)

Set the value of the primary key

  • access: public
void set_id (mixed $value)
  • mixed $value: The value to set
set_inheritance_column (line 1196)

Set the name of the column used for single table inheritance.

  • access: public
void set_inheritance_column (string $name)
  • string $name: The column name to use
set_primary_key (line 1096)

Set the field name used as this class's primary key.

  • access: public
void set_primary_key (string $name)
  • string $name: The primary key field name
set_readonly (line 2731)

Change the setting of the read-only flag for this object

  • access: public
void set_readonly (bool $flag)
  • bool $flag: The value to set for the flag

Redefined in descendants as:
set_sequence_name (line 1376)

Set the name of this class's sequence.

  • access: public
void set_sequence_name (string $name)
  • string $name: The sequence name
set_table_name (line 1118)

Set the name of this class's table.

  • access: public
void set_table_name (string $name)
  • string $name: The table name
set_table_name_prefix (line 1154)

Set the prefix to add to the table name

  • access: public
string set_table_name_prefix (string $prefix)
  • string $prefix: The prefix to use
set_table_name_suffix (line 1174)

Set the suffix to add to the table name

  • access: public
string set_table_name_suffix (string $suffix)
  • string $suffix: The suffix to use
table_exists (line 1422)

Determine whether the table associated with this class exists or not.

  • access: public
bool table_exists ()
table_name (line 1130)

Return the name of this class's table. This function may be overridden by derived classes. By default it infers the name of the table by converting the mixed case name of the class to an underscore format and pluralizing the name.

  • access: public
string table_name ()
table_name_prefix (line 1143)

Return any prefix to add to the table name

  • access: public
string table_name_prefix ()
table_name_suffix (line 1163)

Return any suffix to add to the table name

  • access: public
string table_name_suffix ()
toggle (line 2648)

Sets an attribute with a true value to false and anything else to true.

  • return: A reference to self
  • access: public
ActiveRecord_Base toggle (string $attribute)
  • string $attribute: The name of the attribute to toggle
toggle_and_save (line 2660)

Toggles the named attribute and saves the object.

  • return: The success or failure indicator from the save operation
  • access: public
bool toggle_and_save (string $attribute)
  • string $attribute: The name of the attribute to toggle
type_cast (line 3025)

Type cast a raw column value to a value suitable for use in PHP

code. By default, this method just delegates to the column definition, but it exists as a hook for derived classes to be able to extend the column definition's behavior on an application-wide basis. For example, if you have a different class you want to use to represent dates, or another data type for enums in MySQL. Note that this is not the correct place to handle field-specific type casts for an individual field (for example, if the 'foo' field for class 'Bar' is stored as a string but has a wrapper class that is used in PHP code). Overrides for individual fields are best handled by defining accessor and mutator (get/set) methods for those fields.

  • access: protected
void type_cast (mixed $value, ActiveRecordColumn $col)
  • mixed $value: The value to cast
  • ActiveRecordColumn $col: The column definition (if any) for the value
type_condition (line 2947)

Return condition SQL fragment for single table inheritance

Note: this is considerably less robust than the Rails active record implementation. Rails includes subclasses, whereas this does not. Reason being that it is not only cumbersome to determine descendents in PHP, but it would only ever be practical to determine descendents which have already been loaded/declared. This is only a factor if you have more than two levels of inheritance (in which case it would be a good idea to override this).

  • access: protected
string type_condition ()
update (line 787)

Find an object by id and update the attributes specified in an associative array. The object is automatically saved (validation permitting) and is then returned.

Multiple objects may updated at once by passing an array of ids and an array of attribute arrays. In that case, an array of updated objects is returned.

Example:

  1.    $student new Student();
  2.    $student->update(25array('first_name'=>'Fred''last_name'=>'Smith''major'=>'Computer Science'));
  3.    $student->update(array(510)array(array('first_name'=>'David')array('first_name'=>'Sarah')));

  • access: public
mixed update (mixed $id, array $attrs)
  • mixed $id: The id or list of ids
  • array $attrs: The array of attributes (or array of arrays)
update_all (line 854)

Updates a set of records given a SQL fragment for use inside a

SET clause and an optional set of conditions. As with the conditions option for a find* method, the conditions argument is a SQL fragment suitable for use in a where clause. Either parameter may be a string or an array with the first element containing the SQL fragment and the remaining containing parameters.

Returns a count of records that were updated.

Examples:

  1.   $article new Article();
  2.   $article->update_all("published=0, archived=1, archived_on='2008-03-20'");
  3.   $article->update_all("published=0, archived=1, archived_on='2008-03-20'""archive_after<='2008-03-20'");
  4.   $article->update_all(array("published=0, archived=1, archived_on=?"$today)array("archive_after<=? AND category=?"$today$archiveCategory));

  • access: public
int update_all (string $updates, [mixed $conditions = false])
  • string $updates: The SQL for the SET clause
  • mixed $conditions: Any optional conditions
update_attribute (line 2555)

Updates a single attribute on this object and then saves the object.

  • return: The success or failure indicator from the save operation
  • access: public
bool update_attribute (string $name, mixed $value)
  • string $name: The attribute name
  • mixed $value: The value for the attribute
update_attributes (line 2570)

Updates a list of attriubtes from an associative array and then saves the object.

  • return: The success or failure indicator from the save operation
  • access: public
bool update_attributes (array $attributes)
  • array $attributes: An array whose keys indicate the attributes to update and the values indicate the new attribute values.
update_attributes_or_fail (line 2584)

Operates the same as update_attributes(), but calls save_or_fail, so a RecordNotSaved exception is thrown if the save operation does not succeed.

  • access: public
void update_attributes_or_fail (array $attributes)
  • array $attributes: An array whose keys indicate the attributes to update and the values indicate the new attribute values.
update_record (line 3403)

Update the record associated with the object

  • return: Success or failure indicator
  • access: protected
bool update_record ()
validate (line 3255)

Perform validation checks applicable any time the record is saved. Use errors()->add($attribute, $message) to record any errors.

  • access: protected
void validate ()
validates_confirmation_of (line 1638)

Add one or more validations for fields which have a confirmation field that must contain an identical value.

Example

  1.    // model:
  2.    class User extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_confirmation_of('password');
  5.      }
  6.    }
  7.  
  8.    // HTML form would contain something like:
  9.    // Password:         <input type="password" name="user[password]"><br>
  10.    // Confirm Password: <input type="password" name="user[password_confirmation]">

Options include:

  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_confirmation_of (mixed $attributes, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $options: Any options for the validation
validates_exclusion_of (line 1868)

Add a validation for a field that is allowed to have any value not in a given list.

Example

  1.    // model:
  2.    class User extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_exclusion_of('username'array('admin''root''superuser')array('message'=>'may not be a reserved name'));
  5.      }
  6.    }

Options include:

  • allow_null: If true, validation is skipped when the attribute's value is null
  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_exclusion_of (mixed $attributes, array $invalidValues, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $invalidValues: List of disallowed values
  • array $options: Any options for the validation
validates_format_of (line 1793)

Add a validation for the format of a field. The format is validated using a perl-compatible regular expression.

Example

  1.    // model:
  2.    class Student extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_format_of('ssn''/^\d\d\d-\d\d-\d\d\d\d$/');
  5.        $this->validates_format_of(array('home_phone''work_phone''mobile_phone')'/^(?:\d{3}[ -]?){2}\d{4}(?: *x *\d+)$/'array('message'=>'must be entered as 000-000-0000 x000 where x000 is an optional extension''allow_null'=>true));
  6.      }
  7.    }

Options include:

  • allow_null: If true, validation is skipped when the attribute's value is null
  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_format_of (mixed $attributes, string $pattern, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • string $pattern: Regular expression to use for validation
  • array $options: Any options for the validation
validates_inclusion_of (line 1830)

Add a validation for a field that is only allowed to have a value in a given list.

Example

  1.    // model:
  2.    class Student extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_inclusion_of('degree_type'array('undergraduate''graduate''doctorate'));
  5.      }
  6.    }

Options include:

  • allow_null: If true, validation is skipped when the attribute's value is null
  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_inclusion_of (mixed $attributes, array $validValues, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $validValues: List of allowable values
  • array $options: Any options for the validation
validates_length_of (line 1711)

Add one or more validations for fields lengths. Length refers to the number of characters in the field (string length).

Example

  1.    // model:
  2.    class User extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_length_of(array('first_name''last_name')array('maximum'=>25));
  5.        $this->validates_length_of('password'array('minimum'=>8'maximum'=>14'message'=>'must be between 8 and 14 characters'));
  6.      }
  7.    }

Options include:

  • minimum: Minimum allowed length
  • maximum: Maximum allowed length
  • is: Exact allowed length
  • allow_null: If true, validation is skipped when the attribute's value is null
  • too_short: Custom error message when the value is less than the minimum
  • too_long: Custom error message when the value is greater than the maximum
  • message: Custom error message to use in all cases
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_length_of (mixed $attributes, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $options: Any options for the validation
validates_numericality_of (line 1906)

Add a validation for a field that must be numeric.

Example

  1.    // model:
  2.    class BankAccount extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_numericality_of('balance');
  5.        $this->validates_numericality_of('pin'array('only_integer'=>true));
  6.      }
  7.    }

Options include:

  • only_integer: If true, only an integer value is allowed (by default reals/floats are allowed)
  • allow_null: If true, validation is skipped when the attribute's value is null
  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_numericality_of (mixed $attributes, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $options: Any options for the validation
validates_presence_of (line 1671)

Add one or more validations for fields which may not be empty.

Example

  1.    // model:
  2.    class User extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_presence_of(array('first_name''last_name'));
  5.        $this->validates_presence_of('email'array('message'=>'cannot be blank or contain only zeros or spaces.'));
  6.      }
  7.    }

Options include:

  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_presence_of (mixed $attributes, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $options: Any options for the validation
validates_uniqueness_of (line 1753)

Add one or more validations for fields which must be unique accross records.

Example

  1.    // model:
  2.    class User extends ActiveRecord_Base {
  3.      protected function init_class({
  4.        $this->validates_uniqueness_of('username');
  5.        // or, if users are only unique by some larger grouping, like a domain:
  6.        $this->validates_uniqueness_of('username'array('scope'=>'domain_id'));
  7.      }
  8.    }

Options include:

  • scope: An attribute name or array of names used to limit the scope of the uniqueness constraint
  • case_sensitive: When false, uniqueness is explicitly made case insensitive, otherwise it is dependent on the DB.
  • allow_null: If true, validation is skipped when the attribute's value is null
  • message: Custom error message
  • on: May be 'save', 'create', or 'update'; default is 'save'
  • if: Method name to call for determining if the validation should be run or not (method must accept no arguments and return true or false)

  • access: public
void validates_uniqueness_of (mixed $attributes, [array $options = array()])
  • mixed $attributes: Name of the attribute to validate or an array of attributes to validate
  • array $options: Any options for the validation
validate_find_options (line 2967)

Validates the options provided to a find method

  • access: protected
void validate_find_options ( $options)
  • $options
validate_on_create (line 3263)

Perform validation checks applicable only before saving a new record. Use errors()->add($attribute, $message) to record any errors.

  • access: protected
void validate_on_create ()
validate_on_update (line 3271)

Perform validation checks applicable only before saving an existing record. Use errors()->add($attribute, $message) to record any errors.

  • access: protected
void validate_on_update ()
validate_options (line 2975)

Validates a provided set of options against an allowed set

  • access: protected
void validate_options ( &$options,  &$allowed)
  • &$options
  • &$allowed
validation_name_to_type (line 3559)

Convert a string name of a validation type to the class constant

  • access: protected
int validation_name_to_type (string $name)
  • string $name: The name to convert
values_for_insert (line 3499)

Return the list of all attribute values prepared for use in an insert statement

  • access: protected
string values_for_insert ()
write_attribute (line 3304)

Set the value of a named attribute. Empty strings for numeric fields are treated as NULL.

  • access: protected
void write_attribute (string $name, mixed $value)
  • string $name: The attribute name
  • mixed $value: The new value for the attribute
write_cached_attribute (line 3354)

write_cached_attribute allows the object to store a temporary value

in an attribute cache. Values placed in the cache are ignored when saving or serializing the object. The cache is intended as a place to store attribute values that have been type cast when casting is an expensive operation and for storing dummy attributes (such as a password confirmation field) which are not persisted. The cache is never checked by the default attribute read mechanism. It is the responsibility of the object to implement any logic related to retrieving cached values as the correct time.

  • access: protected
void write_cached_attribute (string $name, mixed $value)
  • string $name: The attribute name
  • mixed $value: The attribute value to cache
__call (line 2361)

Allow dynamic use of accessor and mutator methods for column values. Accessors follow the format column_name() and mutators follow the format set_column_name($arg).

Also enables dynamic finder methods. Dynamic finder methods come in a variety of flavors:

  • find_by_attribute(value): Find the first record whose property "attribute" matches value
  • find_all_by_attribute(value): Find all records whose property "attribute" matches value
  • find_or_initialize_by_attribute(value): Like by_attribute, but will return a new instance with "attribute" initialized to value of no matches are found
  • find_or_create_by_attribute(value): Like initialize_by_attribute, but also saves any new record (validation permitting) before returning it
Multiple attributes may be specified by using _and_ as the separator in the name. All finder methods can also accept an options array as an additional final argument. All options accepted by find_* methods are allowed.

Example:

  1.    $person new Person();
  2.  
  3.    // equivalent to $person->find_first(array("conditions"=>"ssn='123-45-6789'"));
  4.    $person->find_by_ssn('123-45-6789');
  5.  
  6.    // equivalent to $person->find_all(array("conditions"=>"last_name='Smith'));
  7.    $person->find_all_by_last_name('Smith');
  8.  
  9.    // equivalent to $person->find_first(array("conditions"=>"first_name='Suzy' AND last_name='Smith'"));
  10.    $person->find_by_first_name_and_last_name('Suzy''Smith');
  11.  
  12.    // equivalent to $person->find_all(array("conditions"=>"last_name='Smith'", "order"=>"first_name"));
  13.    $person->find_all_by_last_name('Smith'array('order'=>'first_name'));
  14.  
  15.    // eqivalent to $result = $person->find_first(array("conditions"=>"first_name='Suzy' AND last_name='Smith'"));
  16.    //              $result = $result ? $result : $person->create(array('first_name'=>'Suzy', 'last_name'=>'Smith'));
  17.    $result $person->find_or_create_by_first_name_and_last_name('Suzy''Smith');

  • access: public
mixed __call (string $name, array $args)
  • string $name: The name of the method being called.
  • array $args: The arguments being passed
__get (line 2257)

Allow reading of attributes and reader methods as properties

  • access: public
mixed __get (string $name)
  • string $name: The property to retrieve
__isset (line 2298)

Allow use of isset with record attributes as though they were public properties. Unlike other access to properties, this will not defer to to existing reader methods, only actual record properties can be tested.

  • access: public
bool __isset (string $name)
  • string $name: The property to test
__set (line 2228)

Allow writing of attributes and use of set methods as properties

  • access: public
void __set (string $name, mixed $value)
  • string $name: The property to set
  • mixed $value: The value to set
__sleep (line 2435)

Discard meta data and database connections not specific to this

instance prior to serialization

  • access: public
void __sleep ()
__unset (line 2313)

Allow use of unset with record attributes as though they were public properties. Unlike other access to properties, this will not defer to to existing set methods, only actual record properties can be unset.

This has the effect of setting any existing property on the object to NULL.

  • access: public
void __unset (string $name)
  • string $name: The property to unset

Documentation generated on Wed, 25 Apr 2012 09:46:40 -0700 by phpDocumentor 1.4.3