Class Details

The base class for your models.

Defining an ActiveRecord model for a table called people and orders:

 CREATE TABLE people(
   id int primary key auto_increment,
   parent_id int,
   first_name varchar(50),
   last_name varchar(50)
 );

 CREATE TABLE orders(
   id int primary key auto_increment,
   person_id int not null,
   cost decimal(10,2),
   total decimal(10,2)
 );

	

 class Person extends ActiveRecord\Model {
   static $belongs_to = array(
     array('parent', 'foreign_key' => 'parent_id', 'class_name' => 'Person')
   );

   static $has_many = array(
     array('children', 'foreign_key' => 'parent_id', 'class_name' => 'Person'),
     array('orders')
   );

   static $validates_length_of = array(
     array('first_name', 'within' => array(1,50)),
     array('last_name', 'within' => array(1,50))
   );
 }

 class Order extends ActiveRecord\Model {
   static $belongs_to = array(
     array('person')
   );

   static $validates_numericality_of = array(
     array('cost', 'greater_than' => 0),
     array('total', 'greater_than' => 0)
   );

   static $before_save = array('calculate_total_with_tax');

   public function calculate_total_with_tax() {
     $this->total = $this->cost * 0.045;
   }
 }

	

For a more in-depth look at defining models, relationships, callbacks and many other things please consult our Guides.


Class Variables

public static array $alias_attribute = array()

Allows you to create aliases for attributes.

 class Person extends ActiveRecord\Model {
   static $alias_attribute = array(
     'alias_first_name' => 'first_name',
     'alias_last_name' => 'last_name');
 }

 $person = Person::first();
 $person->alias_first_name = 'Tito';
 echo $person->alias_first_name;

	

public static array $attr_accessible = array()

Whitelist of attributes that are checked from mass-assignment calls such as constructing a model or using update_attributes.

This is the opposite of $attr_protected.

 class Person extends ActiveRecord\Model {
   static $attr_accessible = array('first_name','last_name');
 }

 $person = new Person(array(
   'first_name' => 'Tito',
   'last_name' => 'the Grief',
   'id' => 11111));

 echo $person->id; # => null

	

public static array $attr_protected = array()

Blacklist of attributes that cannot be mass-assigned.

This is the opposite of $attr_accessible and the format for defining these are exactly the same.

If the attribute is both accessible and protected, it is treated as protected.

public static string $connection

Set to the name of the connection this Model should use.

public static string $db

Set to the name of the database this Model's table is in.

public static array $delegate = array()

Delegates calls to a relationship.

 class Person extends ActiveRecord\Model {
   static $belongs_to = array(array('venue'),array('host'));
   static $delegate = array(
     array('name', 'state', 'to' => 'venue'),
     array('name', 'to' => 'host', 'prefix' => 'woot'));
 }

	

Can then do:

 $person->state     # same as calling $person->venue->state
 $person->name      # same as calling $person->venue->name
 $person->woot_name # same as calling $person->host->name

	

public Errors $errors

An instance of Errors and will be instantiated once a write method is called.

public static string $primary_key

Set this to override the default primary key name if different from default name of "id".

public static string $sequence

Set this to explicitly specify the sequence name for the table.

public static string $table_name

Set this to explicitly specify the model's table name if different from inferred name.

If your table doesn't follow our table name convention you can set this to the name of your table to explicitly tell ActiveRecord what your table is called.

public static array $VALID_OPTIONS = array('conditions', 'limit', 'offset', 'order', 'select', 'joins', 'include', 'readonly', 'group', 'from', 'having')

A list of valid finder options.


Class Methods

public Model __construct ( [ $attributes = array()] , [ boolean $guard_attributes = true] , [ boolean $instantiating_via_find = false] , [ boolean $new_record = true] )

Constructs a model.

  • array $attributes - Hash containing names and values to mass assign to the model
  • boolean $guard_attributes - Set to true to guard protected/non-accessible attributes
  • boolean $instantiating_via_find - Set to true if this model is being created from a find call
  • boolean $new_record - Set to true if this should be considered a new record

When a user instantiates a new object (e.g.: it was not ActiveRecord that instantiated via a find) then @var $attributes will be mapped according to the schema's defaults. Otherwise, the given $attributes will be mapped via set_attributes_via_mass_assignment.

 new Person(array('first_name' => 'Tito', 'last_name' => 'the Grief'));

	

public static array all ( )

Alias for self::find('all').

public mixed assign_attribute ( string $name , $value , mixed &$value )

Assign a value to an attribute.

  • string $name - Name of the attribute
  • mixed &$value - Value of the attribute
  • $value -
  • return: the attribute value
public array attributes ( )

Returns a copy of the model's attributes hash.

  • return: A copy of the model's attribute data
public boolean attribute_is_dirty ( string $attribute )

Check if a particular attribute has been modified since loading the model.

  • string $attribute - Name of the attribute
  • return: TRUE if it has been modified.
public static Connection connection ( )

Retrieve the connection for this model.

public static int count ( )

Get a count of qualifying records.

  • return: Number of records that matched the query
  • see: Model::find()

 YourModel::count(array('conditions' => 'amount > 3.14159265'));

	

public static Model create ( array $attributes , [ boolean $validate = true] )

Creates a model and saves it to the database.

  • array $attributes - Array of the models attributes
  • boolean $validate - True if the validators should be run
public boolean delete ( )

Deletes this model from the database and returns true if successful.

public static void delete_all ( [ $options = array()] )

Deletes records matching conditions in $options

  • $options -

Does not instantiate models and therefore does not invoke callbacks

Delete all using a hash:

 YourModel::delete_all(array('conditions' => array('name' => 'Tito')));

	

Delete all using an array:

 YourModel::delete_all(array('conditions' => array('name = ?', 'Tito')));

	

Delete all using a string:

 YourModel::delete_all(array('conditions' => 'name = "Tito"));

	

An options array takes the following parameters:

  • conditions: Conditions using a string/hash/array
  • limit: Limit number of records to delete (MySQL & Sqlite only)
  • order: A SQL fragment for ordering such as: 'name asc', 'id desc, name asc' (MySQL & Sqlite only)

public mixed dirty_attributes ( )

Returns hash of attributes that have been modified since loading the model.

  • return: null if no dirty attributes otherwise returns array of dirty attributes.
public static boolean exists ( )

Determine if a record exists.

 SomeModel::exists(123);
 SomeModel::exists(array('conditions' => array('id=? and name=?', 123, 'Tito')));
 SomeModel::exists(array('id' => 123, 'name' => 'Tito'));

	

public static array extract_and_validate_options ( &$array )

Pulls out the options hash from $array if any.

  • array &$array - An array
  • return: A valid options array
public static mixed find ( )

Find records in the database.

  • return: An array of records found if doing a find_all otherwise a single Model object or null if it wasn't found. NULL is only return when doing a first/last find. If doing an all find and no records matched this will return an empty array.
  • throws: RecordNotFound if no options are passed or finding by pk and no records matched

Finding by the primary key:

 # queries for the model with id=123
 YourModel::find(123);

 # queries for model with id in(1,2,3)
 YourModel::find(1,2,3);

 # finding by pk accepts an options array
 YourModel::find(123,array('order' => 'name desc'));

	

Finding by using a conditions array:

 YourModel::find('first', array('conditions' => array('name=?','Tito'),
   'order' => 'name asc'))
 YourModel::find('all', array('conditions' => 'amount > 3.14159265'));
 YourModel::find('all', array('conditions' => array('id in(?)', array(1,2,3))));

	

Finding by using a hash:

 YourModel::find(array('name' => 'Tito', 'id' => 1));
 YourModel::find('first',array('name' => 'Tito', 'id' => 1));
 YourModel::find('all',array('name' => 'Tito', 'id' => 1));

	

An options array can take the following parameters:

  • select: A SQL fragment for what fields to return such as: '*', 'people.*', 'first_name, last_name, id'
  • joins: A SQL join fragment such as: 'JOIN roles ON(roles.user_id=user.id)' or a named association on the model
  • include: TODO not implemented yet
  • conditions: A SQL fragment such as: 'id=1', array('id=1'), array('name=? and id=?','Tito',1), array('name IN(?)', array('Tito','Bob')), array('name' => 'Tito', 'id' => 1)
  • limit: Number of records to limit the query to
  • offset: The row offset to return results from for the query
  • order: A SQL fragment for order such as: 'name asc', 'name asc, id desc'
  • readonly: Return all the models in readonly mode
  • group: A SQL group by fragment

public static Model find_by_pk ( array $values , array $options )

Finder method which will find by a single or array of primary keys for this model.

  • array $values - An array containing values for the pk
  • array $options - An options array
public static array find_by_sql ( string $sql , [ array $values = null] )

Find using a raw SELECT query.

  • string $sql - The raw SELECT query
  • array $values - An array of values for any parameters that needs to be bound
  • return: An array of models

 YourModel::find_by_sql("SELECT * FROM people WHERE name=?",array('Tito'));
 YourModel::find_by_sql("SELECT * FROM people WHERE name='Tito'");

	

public static Model first ( )

Alias for self::find('first').

  • return: The first matched record or null if not found
  • see: Model::find()
public void flag_dirty ( string $name )

Flags an attribute as dirty.

  • string $name - Attribute name
public string get_primary_key ( [ boolean $first = false] )

Retrieve the primary key name.

  • boolean $first - Set to true to return the first value in the pk array only
  • return: The primary key for the model
public string get_real_attribute_name ( string $name )

Returns the actual attribute name if $name is aliased.

  • string $name - An attribute name
public array get_validation_rules ( )

Returns array of validator data for this Model.

  • return: An array containing validator data for this model.

Will return an array looking like:

 array(
   'name' => array(
     array('validator' => 'validates_presence_of'),
     array('validator' => 'validates_inclusion_of', 'in' => array('Bob','Joe','John')),
   'password' => array(
     array('validator' => 'validates_length_of', 'minimum' => 6))
   )
 );

	

public array get_values_for ( array $attributes )

Returns an associative array containing values for all the attributes in $attributes

  • array $attributes - Array containing attribute names
  • return: A hash containing $name => $value
public boolean is_dirty ( )

Returns true if the model has been modified.

  • return: true if modified
public boolean is_invalid ( )

Runs validations and returns true if invalid.

public boolean is_new_record ( )

Determine if the model is a new record.

public static boolean is_options_hash ( array $array , [ bool $throw = true] )

Determines if the specified array is a valid ActiveRecord options array.

  • array $array - An options array
  • bool $throw - True to throw an exception if not valid
  • return: True if valid otherwise valse
  • throws: ActiveRecordException if the array contained any invalid options
public boolean is_readonly ( )

Determine if the model is in read-only mode.

public boolean is_valid ( )

Run validations on model and returns whether or not model passed validation.

public static Model last ( )

Alias for self::find('last')

  • return: The last matched record or null if not found
  • see: Model::find()
public static array pk_conditions ( mixed $args )

Returns a hash containing the names => values of the primary key.

  • mixed $args - Primary key value(s)
  • return: An array in the form array(name => value, ...)
public static object A query ( string $sql , [ array $values = null] )

Helper method to run arbitrary queries against the model's database connection.

  • string $sql - SQL to execute
  • array $values - Bind values, if any, for the query
  • return: PDOStatement object
public void readonly ( [ boolean $readonly = true] )

Flag model as readonly.

  • boolean $readonly - Set to true to put the model into readonly mode
public mixed &read_attribute ( string $name )

Retrieves an attribute's value or a relationship object based on the name passed. If the attribute accessed is 'id' then it will return the model's primary key no matter what the actual attribute name is for the primary key.

  • string $name - Name of an attribute
  • return: The value of the attribute
  • throws: UndefinedPropertyException if name could not be resolved to an attribute, relationship, ...
public static Connection reestablish_connection ( )

Re-establishes the database connection with a new connection.

public Model reload ( )

Reloads the attributes and relationships of this object from the database.

public void reset_dirty ( )

Resets the dirty array.

public boolean save ( [ boolean $validate = true] )

Save the model to the database.

  • boolean $validate - Set to true or false depending on if you want the validators to run or not
  • return: True if the model was saved to the database otherwise false

This function will automatically determine if an INSERT or UPDATE needs to occur. If a validation or a callback for this model returns false, then the model will not be saved and this will return false.

If saving an existing model only data that has changed will be saved.

public void set_attributes ( $attributes )

Mass update the model with data from an attributes hash.

  • array $attributes - An array containing data to update in the form array(name => value, ...)

Unlike update_attributes() this method only updates the model's data but DOES NOT save it to the database.

public void set_relationship_from_eager_load ( [ Model $model = null] , $name $name )

Add a model to the given named ($name) relationship.

  • Model $model -
  • $name $name - of relationship for this table
public void set_timestamps ( )

Updates a model's timestamps.

public static Table table ( )

Returns the Table object for this model.

Be sure to call in static scoping: static::table()

public static string table_name ( )

Retrieves the name of the table for this Model.

public array to_array ( [ $options = array()] )

Returns an Array representation of this model.

  • array $options - An array containing options for json serialization (see Serialization for valid options)
public string to_csv ( [ $options = array()] )

Returns an CSV representation of this model.

  • array $options - An array containing options for csv serialization (see Serialization for valid options)

Can take optional delimiter and enclosure (defaults are , and double quotes)

Ex:

 ActiveRecord\CsvSerializer::$delimiter=';';
 ActiveRecord\CsvSerializer::$enclosure='';
 YourModel::find('first')->to_csv(array('only'=>array('name','level')));
 returns: Joe,2

 YourModel::find('first')->to_csv(array('only_header'=>true,'only'=>array('name','level')));
 returns: name,level

	

public string to_json ( [ $options = array()] )

Returns a JSON representation of this model.

  • array $options - An array containing options for json serialization (see Serialization for valid options)
public string to_xml ( [ $options = array()] )

Returns an XML representation of this model.

  • array $options - An array containing options for xml serialization (see Serialization for valid options)
public static boolean transaction ( Closure $closure )

Executes a block of code inside a database transaction.

  • Closure $closure - The closure to execute. To cause a rollback have your closure return false or throw an exception.
  • return: True if the transaction was committed, False if rolled back.

 YourModel::transaction(function()
 {
   YourModel::create(array("name" => "blah"));
 });

	

If an exception is thrown inside the closure the transaction will automatically be rolled back. You can also return false from your closure to cause a rollback:

 YourModel::transaction(function()
 {
   YourModel::create(array("name" => "blah"));
   throw new Exception("rollback!");
 });

 YourModel::transaction(function()
 {
   YourModel::create(array("name" => "blah"));
   return false; # rollback!
 });

	

public static void update_all ( [ $options = array()] )

Updates records using set in $options

  • $options -

Does not instantiate models and therefore does not invoke callbacks

Update all using a hash:

 YourModel::update_all(array('set' => array('name' => "Bob")));

	

Update all using a string:

 YourModel::update_all(array('set' => 'name = "Bob"'));

	

An options array takes the following parameters:

  • set: String/hash of field names and their values to be updated with
  • conditions: Conditions using a string/hash/array
  • limit: Limit number of records to update (MySQL & Sqlite only)
  • order: A SQL fragment for ordering such as: 'name asc', 'id desc, name asc' (MySQL & Sqlite only)

public boolean update_attribute ( string $name , mixed $value )

Updates a single attribute and saves the record without going through the normal validation procedure.

  • string $name - Name of attribute
  • mixed $value - Value of the attribute
  • return: True if successful otherwise false
public boolean update_attributes ( array $attributes )

Mass update the model with an array of attribute data and saves to the database.

  • array $attributes - An attribute data array in the form array(name => value, ...)
  • return: True if successfully updated and saved otherwise false
public array values_for ( array $attribute_names )

Helper to return a hash of values for the specified attributes.

  • array $attribute_names - Array of attribute names
  • return: An array in the form array(name => value, ...)
public array values_for_pk ( )

Helper that creates an array of values for the primary key(s).

  • return: An array in the form array(key_name => value, ...)
public mixed __call ( string $method , mixed $args )

Enables the use of build|create for associations.

  • string $method - Name of method
  • mixed $args - Method args
public static Model __callStatic ( string $method , mixed $args )

Enables the use of dynamic finders.

  • string $method - Name of method
  • mixed $args - Method args

Dynamic finders are just an easy way to do queries quickly without having to specify an options array with conditions in it.

 SomeModel::find_by_first_name('Tito');
 SomeModel::find_by_first_name_and_last_name('Tito','the Grief');
 SomeModel::find_by_first_name_or_last_name('Tito','the Grief');
 SomeModel::find_all_by_last_name('Smith');
 SomeModel::count_by_name('Bob')
 SomeModel::count_by_name_or_state('Bob','VA')
 SomeModel::count_by_name_and_state('Bob','VA')

	

You can also create the model if the find call returned no results:

 Person::find_or_create_by_name('Tito');

 # would be the equivalent of
 if (!Person::find_by_name('Tito'))
   Person::create(array('Tito'));

	

Some other examples of find_or_create_by:

 Person::find_or_create_by_name_and_id('Tito',1);
 Person::find_or_create_by_name_and_id(array('name' => 'Tito', 'id' => 1));

	

public void __clone ( )
public mixed &__get ( string $name )

Magic method which delegates to read_attribute(). This handles firing off getter methods, as they are not checked/invoked inside of read_attribute(). This circumvents the problem with a getter being accessed with the same name as an actual attribute.

  • string $name - Name of an attribute

You can also define customer getter methods for the model.

EXAMPLE:

 class User extends ActiveRecord\Model {

   # define custom getter methods. Note you must
   # prepend get_ to your method name:
   function get_middle_initial() {
     return $this->middle_name{0};
   }
 }

 $user = new User();
 echo $user->middle_name;  # will call $user->get_middle_name()

	

If you define a custom getter with the same name as an attribute then you will need to use read_attribute() to get the attribute's value. This is necessary due to the way __get() works.

For example, assume 'name' is a field on the table and we're defining a custom getter for 'name':

 class User extends ActiveRecord\Model {

   # INCORRECT way to do it
   # function get_name() {
   #   return strtoupper($this->name);
   # }

   function get_name() {
     return strtoupper($this->read_attribute('name'));
   }
 }

 $user = new User();
 $user->name = 'bob';
 echo $user->name; # => BOB

	

public boolean __isset ( string $attribute_name )

Determines if an attribute exists for this Model.

  • string $attribute_name -
public mixed __set ( string $name , mixed $value )

Magic allows un-defined attributes to set via $attributes.

  • string $name - Name of attribute, relationship or other to set
  • mixed $value - The value

You can also define customer setter methods for the model.

EXAMPLE:

 class User extends ActiveRecord\Model {

   # define custom setter methods. Note you must
   # prepend set_ to your method name:
   function set_password($plaintext) {
     $this->encrypted_password = md5($plaintext);
   }
 }

 $user = new User();
 $user->password = 'plaintext';  # will call $user->set_password('plaintext')

	

If you define a custom setter with the same name as an attribute then you will need to use assign_attribute() to assign the value to the attribute. This is necessary due to the way __set() works.

For example, assume 'name' is a field on the table and we're defining a custom setter for 'name':

 class User extends ActiveRecord\Model {

   # INCORRECT way to do it
   # function set_name($name) {
   #   $this->name = strtoupper($name);
   # }

   function set_name($name) {
     $this->assign_attribute('name',strtoupper($name));
   }
 }

 $user = new User();
 $user->name = 'bob';
 echo $user->name; # => BOB

	

public void __wakeup ( )