Class AkActiveRecord

(line 184)

Description

AkObject
   |
   --AkBaseModel
      |
      --AkAssociatedActiveRecord
         |
         --AkActiveRecord

Located in File: /AkActiveRecord.php

Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.

See the mapping rules in table_name and the full example in README.txt for more insight.

== Creation ==

Active Records accepts constructor parameters either in an array or as a list of parameters in a specific format. The array method is especially useful when you're receiving the data from somewhere else, like a HTTP request. It works like this:

  1.    $user = new User(array('name' => 'David''occupation' => 'Code Artist'));
  2.    echo $user->name// Will print "David"

You can also use a parameter list initialization.:

$user = new User('name->', 'David', 'occupation->', 'Code Artist');

And of course you can just create a bare object and specify the attributes after the fact:

  1.    $user = new User();
  2.    $user->name = 'David';
  3.    $user->occupation = 'Code Artist';

== Conditions ==

Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement. The array form is to be used when the condition input is tainted and requires sanitization. The string form can be used for statements that doesn't involve tainted data. Examples:

  1.    class User extends ActiveRecord
  2.    {
  3.      function authenticateUnsafely($user_name$password)
  4.      {
  5.           return findFirst("user_name = '$user_name' AND password = '$password'");
  6.      }
  7.  
  8.      function authenticateSafely($user_name$password)
  9.      {
  10.           return findFirst("user_name = ? AND password = ?"$user_name$password);
  11.      }
  12.     }

The <tt>authenticateUnsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection attacks if the <tt>$user_name</tt> and <tt>$password</tt> parameters come directly from a HTTP request. The <tt>authenticateSafely</tt> method, on the other hand, will sanitize the <tt>$user_name</tt> and <tt>$password</tt> before inserting them in the query, which will ensure that an attacker can't escape the query and fake the login (or worse).

When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing the question marks with symbols and supplying a hash with values for the matching symbol keys:

  1.    $Company->findFirst(
  2.               "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
  3.                array(':id' => 3':name' => "37signals"':division' => "First"':accounting_date' => '2005-01-01')
  4.              );

== Accessing attributes before they have been type casted ==

Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first. That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model has a balance attribute, you can call $Account->balance_before_type_cast or $Account->id_before_type_cast.

This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn't what you want.

== Saving arrays, hashes, and other non-mappable objects in text columns ==

Active Record can serialize any object in text columns. To do so, you must specify this with by setting the attribute serialize with a comma separated list of columns or an array. This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:

  1.    class User extends ActiveRecord
  2.    {
  3.       var $serialize 'preferences';
  4.    }
  5.  
  6.    $User = new User(array('preferences'=>array("background" => "black""display" => 'large')));
  7.    $User->find($user_id);
  8.    $User->preferences // array("background" => "black", "display" => 'large')

== Single table inheritance ==

Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed by overwriting <tt>AkActiveRecord->_inheritanceColumn</tt>). This means that an inheritance looking like this:

  1.    class Company extends ActiveRecord{}
  2.    class Firm extends Company{}
  3.    class Client extends Company{}
  4.    class PriorityClient extends Client{}

When you do $Firm->create('name =>', "akelos"), this record will be saved in the companies table with type = "Firm". You can then fetch this row again using $Company->find('first', "name = '37signals'") and it will return a Firm object.

If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

Note, all the attributes for all the cases are kept in the same table. Read more: http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html

== Connection to multiple databases in different models ==

Connections are usually created through AkActiveRecord->establishConnection and retrieved by AkActiveRecord->connection. All classes inheriting from AkActiveRecord will use this connection. But you can also set a class-specific connection. For example, if $Course is a AkActiveRecord, but resides in a different database you can just say $Course->establishConnection and $Course and all its subclasses will use this connection instead.

Active Records will automatically record creation and/or update timestamps of database objects if fields of the names created_at/created_on or updated_at/updated_on are present. Date only: created_on, updated_on Date and time: created_at, updated_at

This behavior can be turned off by setting <tt>$this->_recordTimestamps = false</tt>.



Class Variables

Summary:

Class Constants

Summary:

Method Detail

Summary:
AkActiveRecord __construct ()
void __destruct ()
void actsAs ( $behaviour, [ $options = array()])
void actsLike ()
void addCombinedAttributeConfiguration ( $attribute)
void addConditions ( &$sql, [ $conditions = null], [ $table_alias = null])
void addError ( $attribute, [ $message = 'invalid'])
void addErrorOnBlank ( $attribute_names, [ $message = 'blank'])
void addErrorOnBoundaryBreaking ( $attribute_names,  $range_begin,  $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])
void addErrorOnBoundryBreaking ( $attributes,  $range_begin,  $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])
void addErrorOnEmpty ( $attribute_names, [ $message = 'empty'])
void addErrorToBase ( $message)
void &addObserver ( &$observer)
void afterCreate ()
void afterDestroy ()
void afterSave ()
void afterUpdate ()
void afterValidation ()
void average ( $column_name, [ $options = array()])
void beforeCreate ()
void beforeDestroy ()
void beforeSave ()
void beforeUpdate ()
void calculate ( $operation,  $column_name, [ $options = array()])
void castAttributeForDatabase ( $column_name,  $value, [ $add_quotes = true])
void castAttributeFromDatabase ( $column_name,  $value)
void clearErrors ()
void cloneRecord ()
void collect ( &$source_array,  $key_index,  $value_index)
void composeCombinedAttribute ( $combined_attribute)
void constructFinderSql ( $options, [ $select_from_prefix = 'default'])
void count ()
void countBySql ( $sql)
void countErrors ()
void &create ([ $attributes = null])
void createOrUpdate ([ $validate = true])
void dbug ()
void dbugging ([ $trace_this_on_debug_mode = null])
void debug ([ $data = 'active_record_class'], [ $_functions = 0])
void decomposeCombinedAttribute ( $combined_attribute, [ $used_on_combined_fields = false])
void decrementAndSaveAttribute ( $attribute)
void decrementAttribute ( $attribute)
void decrementCounter ( $counter_name,  $id, [ $difference = 1])
void delete ( $id)
void deleteAll ([ $conditions = null])
void descendsFromActiveRecord ( &$object)
void destroy ([ $id = null])
void destroyAll ( $conditions)
void errorsToString ([ $print = false])
void &establishConnection ([ $specification_or_profile = AK_DEFAULT_DATABASE_PROFILE])
void exists ( $id)
void &find ()
void &findAll ()
void &findAllBy ()
void &findBy ()
void &findBySql ( $sql, [ $limit = null], [ $offset = null], [ $bindings = null])
void &findFirst ()
void &findFirstBy ()
void &findLastBy ()
void &findOrCreateBy ()
void freeze ()
void get ([ $attribute = null], [ $inspect_for_callback_child_method = true])
string getAkelosDataType ( &$adodb_column_object)
void getArrayFromAkString ( $string)
void getAttribute ( $attribute, [ $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS])
void getAttributeBeforeTypeCast ( $attribute)
void getAttributeByLocale ( $attribute,  $locale)
void getAttributeCaption ( $attribute)
void getAttributeCondition ( $argument)
void getAttributeLocales ( $attribute)
void getAttributes ()
void getAttributesQuoted ( $attributes_array)
void getBaseErrors ()
void getColumnNames ()
void getColumns ([ $force_reload = false])
void getColumnScale ( $column_name)
void getColumnSettings ([ $force_reload = false])
void getColumnsForAttributes ( $attributes)
void getColumnType ( $column_name)
void getCombinedSubattributes ( $attribute)
void getConditions ( $conditions, [ $prefix = ''], [ $model_name = null])
void &getConnection ()
void getDisplayField ()
void getErrors ()
void getErrorsOn ( $attribute)
void getId ()
void &getObservers ()
void getOnlyAvailableAttributes ( $attributes)
void getPrimaryKey ()
void getSanitizedConditionsArray ( $conditions_array)
void getSubclasses ()
void getTableName ([ $modify_for_associations = true])
void getType ()
boolean hasAttribute (string $attribute)
void hasBeenModified ()
boolean hasColumn ( $column, string $name)
void hasErrors ()
void incrementAndSaveAttribute ( $attribute)
void incrementAttribute ( $attribute)
void incrementCounter ( $counter_name,  $id, [ $difference = 1])
void init ([ $attributes = array()])
void initiateAttributeToNull ( $attribute)
void &instantiate ( $record, [ $set_as_new = true])
void isAttributePresent ( $attribute)
void isBlank ([ $value = null])
boolean isCombinedAttribute (string $attribute)
void isConnected ()
void isFrozen ()
void isInvalid ( $attribute)
void isNewRecord ()
void isValid ()
void loadColumnsSettings ([ $force_reload = false])
void maximum ( $column_name, [ $options = array()])
void minimum ( $column_name, [ $options = array()])
void newRecord ( $attributes)
true notifyObservers ([ $method = null])
void &objectCache ()
void parseAkelosArgs ( &$args)
void quotedId ()
void reload ()
void requiredForCombination ( $attribute)
void save ([ $validate = true])
void select ( &$source_array)
void set ( $attribute, [ $value = null], [ $inspect_for_callback_child_method = true], [ $compose_after_set = true])
void setAttribute ( $attribute,  $value, [ $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS], [ $compose_after_set = true])
void setAttributeByLocale ( $attribute,  $value,  $locale)
void setAttributeLocales ( $attribute, [ $values = array()])
void setAttributes ( $attributes, [ $override_attribute_protection = false])
void setColumnSettings ( $column_name,  $column_object)
void &setConnection ([ $db_adapter = null])
void setDisplayField ( $attribute_name)
void setId ( $value)
void setInheritanceColumn ( $column_name)
void setObservableState ( $state_message)
void setPrimaryKey ([ $primary_key = 'id'])
void setSerializeAttribute ( $attr_name, [ $class_name = null])
void setTableName ([ $table_name = null], [ $check_for_existence = AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES], [ $check_mode = false])
void sum ( $column_name, [ $options = array()])
void t ( $string, [ $array = null])
void toggleAttribute ( $attribute)
void toggleAttributeAndSave ( $attribute)
void toJson ()
void toString ([ $print = false])
void toYaml ([array $data = null])
void transactionFail ()
void typeCondition ([ $table_alias = null])
void update ( $id,  $attributes)
void updateAll ( $updates, [ $conditions = null])
void updateAttribute ( $name,  $value, [ $should_validate = true])
void updateAttributes ( $attributes, [ $object = null])
void validate ()
void validatesAcceptanceOf (accept $attribute_names, [ $message = 'accepted'], [ $accept = 1])
void validatesAssociated ( $attribute_names, [ $message = 'invalid'])
void validatesConfirmationOf ( $attribute_names, [ $message = 'confirmation'])
void validatesExclusionOf ( $attribute_names,  $array_of_possibilities, [ $message = 'exclusion'], [ $allow_null = false])
void validatesFormatOf ( $attribute_names,  $regular_expression, [ $message = 'invalid'], [ $regex_function = 'preg_match'])
void validatesInclusionOf ( $attribute_names,  $array_of_possibilities, [ $message = 'inclusion'], [ $allow_null = false])
void validatesLengthOf ( $attribute_names, [ $options = array()])
void validatesNumericalityOf ( $attribute_names, [ $message = 'not_a_number'], [ $only_integer = false], [ $allow_null = false])
void validatesPresenceOf ( $attribute_names, [ $message = 'blank'])
void validatesSizeOf ( $attribute_names, [ $options = array()])
void validatesUniquenessOf ( $attribute_names, [ $options = array()])
void yieldEachError ()
void yieldError ( $message)
void _destroy ()
void _extractConditionsFromArgs ( $args,  $options)
void _extractOptionsFromArgs ( &$args)
void _extractValueFromDefault ( $default)
void &_findEvery ( $options)
void &_findFromIds ( $ids,  $options)
void &_findInitial ( $options)
void _getFindBySqlAndColumns ( $find_by_sql,  &$query_values)
string _getVariableSqlCondition ( $variable_condition)
void _isOptionsHash ( $options)
void _sanitizeConditionsVariables ( &$options)
void _validateFindOptions ( &$options)

Constructor __construct (line 257)

AkActiveRecord __construct( )

Overrides : AkObject::__construct() Class constructor, overriden in descendant classes

Info

Destructor __destruct (line 313)

void __destruct( )

Overrides : AkObject::__destruct() Class destructor, overriden in descendant classes

Info

Method actsAs (line 4471)

void actsAs( $behaviour, [ $options = array()])

actAs provides a method for extending Active Record models.

Example: $this->actsAs('list', array('scope' => 'todo_list'));

Parameters

  • $behaviour:
  • $options:

Info

Method actsLike (line 4540)

void actsLike( )

Returns a comma separated list of possible acts like (active record, nested set, list)....

Info

Method addCombinedAttributeConfiguration (line 2154)

void addCombinedAttributeConfiguration( $attribute)

Parameters

  • $attribute:

Info

Method addConditions (line 1370)

void addConditions( &$sql, [ $conditions = null], [ $table_alias = null])

Adds a sanitized version of $conditions to the $sql string. Note that the passed $sql string is changed.

Parameters

  • &$sql:
  • $conditions:
  • $table_alias:

Info

Method addError (line 4271)

void addError( $attribute, [ $message = 'invalid'])

Adds an error message ($message) to the ($attribute), which will be returned on a call to <tt>getErrorsOn($attribute)</tt> for the same attribute and ensure that this error object returns false when asked if <tt>hasErrors</tt>. More than one error can be added to the same $attribute in which case an array will be returned on a call to <tt>getErrorsOn($attribute)</tt>.

If no $message is supplied, "invalid" is assumed.

Parameters

  • $attribute:
  • $message:

Info

Method addErrorOnBlank (line 4294)

void addErrorOnBlank( $attribute_names, [ $message = 'blank'])

Will add an error message to each of the attributes in $attributes that is blank (using $this->isBlank).

Parameters

  • $attribute_names:
  • $message:

Info

Method addErrorOnBoundaryBreaking (line 4309)

void addErrorOnBoundaryBreaking( $attribute_names, $range_begin, $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])

Will add an error message to each of the attributes in $attributes that has a length outside of the passed boundary $range.

If the length is above the boundary, the too_long_message message will be used. If below, the too_short_message.

Parameters

  • $attribute_names:
  • $range_begin:
  • $range_end:
  • $too_long_message:
  • $too_short_message:

Info

Method addErrorOnBoundryBreaking (line 4326)

void addErrorOnBoundryBreaking( $attributes, $range_begin, $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])

Parameters

  • $attributes:
  • $range_begin:
  • $range_end:
  • $too_long_message:
  • $too_short_message:

Info

Method addErrorOnEmpty (line 4280)

void addErrorOnEmpty( $attribute_names, [ $message = 'empty'])

Will add an error message to each of the attributes in $attributes that is empty.

Parameters

  • $attribute_names:
  • $message:

Info

Method addErrorToBase (line 4250)

void addErrorToBase( $message)

Adds an error to the base object instead of any particular attribute. This is used to report errors that doesn't tie to any specific attribute, but rather to the object as a whole. These error messages doesn't get prepended with any field name when iterating with yieldEachFullError, so they should be complete sentences.

Parameters

  • $message:

Info

Method addObserver (line 4203)

void &addObserver( &$observer)

Register the reference to an object object

Parameters

  • &$observer:

Info

Method afterCreate (line 3421)

void afterCreate( )

Info

Method afterDestroy (line 3422)

void afterDestroy( )

Info

Method afterSave (line 3424)

void afterSave( )

Info

Method afterUpdate (line 3417)

void afterUpdate( )

Info

Method afterValidation (line 3418)

void afterValidation( )

Info

Method afterValidationOnCreate (line 3419)

void afterValidationOnCreate( )

Info

Method afterValidationOnUpdate (line 3420)

void afterValidationOnUpdate( )

Info

Method attributesFromColumnDefinition (line 2518)

void attributesFromColumnDefinition( )

Initializes the attributes array with keys matching the columns from the linked table and the values matching the corresponding default value of that column, so that a new instance, or one populated from a passed-in array, still has all the attributes that instances loaded from the database would.

Info

Method average (line 4885)

void average( $column_name, [ $options = array()])

Calculates average value on a given column. The value is returned as a float. See #calculate for examples with options.

$Person->average('age');

Parameters

  • $column_name:
  • $options:

Info

Method beforeCreate (line 3411)

void beforeCreate( )

Callbacks are hooks into the life-cycle of an Active Record object that allows you to trigger logic

before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting beforeDestroy) or to massage attributes before they're validated (by overwriting beforeValidation). As an example of the callbacks initiated, consider the AkActiveRecord->save() call:

  • (-) save()
  • (-) needsValidation()
  • (1) beforeValidation()
  • (2) beforeValidationOnCreate() / beforeValidationOnUpdate()
  • (-) validate()
  • (-) validateOnCreate()
  • (4) afterValidation()
  • (5) afterValidationOnCreate() / afterValidationOnUpdate()
  • (6) beforeSave()
  • (7) beforeCreate() / beforeUpdate()
  • (-) create()
  • (8) afterCreate() / afterUpdate()
  • (9) afterSave()
  • (10) afterDestroy()
  • (11) beforeDestroy()

That's a total of 15 callbacks, which gives you immense power to react and prepare for each state in the Active Record lifecycle.

Examples: class CreditCard extends ActiveRecord { // Strip everything but digits, so the user can specify "555 234 34" or // "5552-3434" or both will mean "55523434" function beforeValidationOnCreate { if(!empty($this->number)){ $this->number = ereg_replace('[^0-9]*','',$this->number); } } }

class Subscription extends ActiveRecord { // Note: This is not implemented yet var $beforeCreate = 'recordSignup';

function recordSignup() { $this->signed_up_on = date("Y-m-d"); } }

class Firm extends ActiveRecord { //Destroys the associated clients and people when the firm is destroyed // Note: This is not implemented yet var $beforeDestroy = array('destroyAssociatedPeople', 'destroyAssociatedClients');

function destroyAssociatedPeople() { $Person = new Person(); $Person->destroyAll("firm_id=>", $this->id); }

function destroyAssociatedClients() { $Client = new Client(); $Client->destroyAll("client_of=>", $this->id); } }

== Canceling callbacks ==

If a before* callback returns false, all the later callbacks and the associated action are cancelled. If an after* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

Override this methods to hook Active Records

Info

  • access - public

Method beforeDestroy (line 3423)

void beforeDestroy( )

Info

Method beforeSave (line 3415)

void beforeSave( )

Info

Method beforeUpdate (line 3416)

void beforeUpdate( )

Info

Method beforeValidation (line 3412)

void beforeValidation( )

Info

Method beforeValidationOnCreate (line 3413)

void beforeValidationOnCreate( )

Info

Method beforeValidationOnUpdate (line 3414)

void beforeValidationOnUpdate( )

Info

Method calculate (line 4947)

void calculate( $operation, $column_name, [ $options = array()])

This calculates aggregate values in the given column: Methods for count, sum, average, minimum, and maximum have been added as shortcuts.

Options such as 'conditions', 'order', 'group', 'having', and 'joins' can be passed to customize the query.

There are two basic forms of output: * Single aggregate value: The single value is type cast to integer for COUNT, float for AVG, and the given column's type for everything else. * Grouped values: This returns an ordered hash of the values and groups them by the 'group' option. It takes a column name.

$values = $Person->maximum('age', array('group' => 'last_name')); echo $values["Drake"] => 43

Options: * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array( "user_name = ?", username ). See conditions in the intro. * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table's columns. * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join. * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...

Examples: $Person->calculate('count', 'all'); // The same as $Person->count(); $Person->average('age'); // SELECT AVG(age) FROM people... $Person->minimum('age', array('conditions' => array('last_name != ?', 'Drake'))); // Selects the minimum age for everyone with a last name other than 'Drake' $Person->minimum('age', array('having' => 'min(age) > 17', 'group' => 'last'_name)); // Selects the minimum age for any family without any minors

Parameters

  • $operation:
  • $column_name:
  • $options:

Info

Method castAttributeForDatabase (line 3151)

void castAttributeForDatabase( $column_name, $value, [ $add_quotes = true])

Parameters

  • $column_name:
  • $value:
  • $add_quotes:

Info

Method castAttributeFromDatabase (line 3215)

void castAttributeFromDatabase( $column_name, $value)

Parameters

  • $column_name:
  • $value:

Info

Method clearErrors (line 4421)

void clearErrors( )

Removes all the errors that have been added.

Info

Method cloneRecord (line 343)

void cloneRecord( )

Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.

Info

Method collect (line 4729)

void collect( &$source_array, $key_index, $value_index)

Collect is a function for selecting items from double depth array like the ones returned by the AkActiveRecord. This comes useful when you just need some fields for generating tables, select lists with only desired fields.

$people_for_select = Ak::select($People->find(),'id','email');

Returns something like: array ( array ('10' => 'jose@example.com'), array ('15' => 'alicia@example.com'), array ('16' => 'hilario@example.com'), array ('18' => 'bermi@example.com') );

Parameters

  • &$source_array:
  • $key_index:
  • $value_index:

Info

Method composeCombinedAttribute (line 2185)

void composeCombinedAttribute( $combined_attribute)

Parameters

  • $combined_attribute:

Info

Method composeCombinedAttributes (line 2174)

void composeCombinedAttributes( )

Info

Method constructFinderSql (line 1347)

void constructFinderSql( $options, [ $select_from_prefix = 'default'])

Parameters

  • $options:
  • $select_from_prefix:

Info

Method count (line 4873)

void count( )

Count operates using three different approaches.

* Count all: By not passing any parameters to count, it will return a count of all the rows for the model. * Count by conditions or joins * Count using options will find the row count matched by the options used.

The last approach, count using options, accepts an option hash as the only parameter. The options are:

* <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array("user_name = ?", $username ). See conditions in the intro. * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join. * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...

Examples for counting all: $Person->count(); // returns the total count of all people

Examples for count by +conditions+ and +joins+ (this has been deprecated): $Person->count("age > 26"); // returns the number of people older than 26 $Person->find("age > 26 AND job.salary > 60000", "LEFT JOIN jobs on jobs.person_id = ".$Person->id); // returns the total number of rows matching the conditions and joins fetched by SELECT COUNT(*).

Examples for count with options: $Person->count('conditions' => "age > 26"); $Person->count('conditions' => "age > 26 AND job.salary > 60000", 'joins' => "LEFT JOIN jobs on jobs.person_id = $Person->id"); // finds the number of rows matching the conditions and joins. $Person->count('id', 'conditions' => "age > 26"); // Performs a COUNT(id) $Person->count('all', 'conditions' => "age > 26"); // Performs a COUNT(*) ('all' is an alias for '*')

Note: $Person->count('all') will not work because it will use 'all' as the condition. Use $Person->count() instead.

Info

Method countBySql (line 578)

void countBySql( $sql)

Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.

$Product->countBySql("SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id");

Parameters

  • $sql:

Info

Method countErrors (line 4430)

void countErrors( )

Returns the total number of errors added. Two errors added to the same attribute will be counted as such with this as well.

Info

Method create (line 393)

void &create( [ $attributes = null])

Overrides : AkAssociatedActiveRecord::create() parent method not documented

Creates an object, instantly saves it as a record (if the validation permits it), and returns it.

If the save fail under validations, the unsaved object is still returned.

Parameters

  • $attributes:

Info

Method createOrUpdate (line 410)

void createOrUpdate( [ $validate = true])

Parameters

  • $validate:

Info

Method dbug (line 4559)

void dbug( )

Info

Method dbugging (line 4599)

void dbugging( [ $trace_this_on_debug_mode = null])

Parameters

  • $trace_this_on_debug_mode:

Info

Method debug (line 4610)

void debug( [ $data = 'active_record_class'], [ $_functions = 0])

Parameters

  • $data:
  • $_functions:

Info

Method decomposeCombinedAttribute (line 2260)

void decomposeCombinedAttribute( $combined_attribute, [ $used_on_combined_fields = false])

Parameters

  • $combined_attribute:
  • $used_on_combined_fields:

Info

Method decomposeCombinedAttributes (line 2250)

void decomposeCombinedAttributes( )

Info

Method decrementAndSaveAttribute (line 1854)

void decrementAndSaveAttribute( $attribute)

Decrements the attribute and saves the record.

Parameters

  • $attribute:

Info

Method decrementAttribute (line 1843)

void decrementAttribute( $attribute)

Initializes the attribute to zero if null and subtracts one. Only makes sense for number-based attributes. Returns attribute value.

Parameters

  • $attribute:

Info

Method decrementCounter (line 1835)

void decrementCounter( $counter_name, $id, [ $difference = 1])

Works like AkActiveRecord::incrementCounter, but decrements instead.

Parameters

  • $counter_name:
  • $id:
  • $difference:

Info

Method delete (line 723)

void delete( $id)

Deletes the record with the given id without instantiating an object first. If an array of ids is provided, all of them are deleted.

Parameters

  • $id:

Info

Method deleteAll (line 742)

void deleteAll( [ $conditions = null])

Deletes all the records that matches the condition without instantiating the objects first (and hence not calling the destroy method). Example:

  1. $Post->destroyAll("person_id = 5 AND (category = 'Something' OR category = 'Else')");

Important note: Conditions are not sanitized yet so beware of accepting variable conditions when using this function

Parameters

  • $conditions:

Info

Method descendsFromActiveRecord (line 1522)

void descendsFromActiveRecord( &$object)

Parameters

  • &$object:

Info

Method destroy (line 762)

void destroy( [ $id = null])

Destroys the record with the given id by instantiating the object and calling destroy (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted).

Parameters

  • $id:

Info

Method destroyAll (line 822)

void destroyAll( $conditions)

Destroys the objects for all the records that matches the condition by instantiating each object and calling the destroy method.

Example:

$Person->destroyAll("last_login < '2004-04-04'");

Parameters

  • $conditions:

Info

Method errorsToString (line 4441)

void errorsToString( [ $print = false])

Parameters

  • $print:

Info

Method establishConnection (line 2342)

void &establishConnection( [ $specification_or_profile = AK_DEFAULT_DATABASE_PROFILE])

Establishes the connection to the database. Accepts either a profile name specified in config/config.php or an array as input where the 'type' key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):

$AkActiveRecord->establishConnection('development'); $AkActiveRecord->establishConnection('super_user');

$AkActiveRecord->establishConnection( array( 'type' => "mysql", 'host' => "localhost", 'username' => "myuser", 'password' => "mypass", 'database' => "somedatabase" ));

Example for SQLite database:

$AkActiveRecord->establishConnection( array( 'type' => "sqlite", 'dbfile' => "path/to/dbfile" ) )

Parameters

  • $specification_or_profile:

Info

Method exists (line 853)

void exists( $id)

Returns true if the given id represents the primary key of a record in the database, false otherwise. Example:

$Person->exists(5);

Parameters

  • $id:

Info

Method find (line 903)

void &find( )

Overrides : AkAssociatedActiveRecord::find() parent method not documented

Find operates with three different retrieval approaches: * Find by id: This can either be a specific id find(1), a list of ids find(1, 5, 6), or an array of ids find(array(5, 6, 10)). If no record can be found for all of the listed ids, then RecordNotFound will be raised.

* Find first: This will return the first record matched by the options used. These options can either be specific conditions or merely an order. If no record can matched, false is returned. * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned.

All approaches accepts an $option array as their last parameter. The options are:

'conditions' => An SQL fragment like "administrator = 1" or array("user_name = ?" => $username). See conditions in the intro. 'order' => An SQL fragment like "created_at DESC, name". 'limit' => An integer determining the limit on the number of rows that should be returned. 'offset' => An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows. 'joins' => An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = $id". (Rarely needed). 'include' => Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. See eager loading under Associations.

Examples for find by id:

  1.    $Person->find(1);       // returns the object for ID = 1
  2.    $Person->find(126)// returns an array for objects with IDs in (1, 2, 6), Returns false if any of those IDs is not available
  3.    $Person->find(array(717))// returns an array for objects with IDs in (7, 17)
  4.    $Person->find(array(1));     // returns an array for objects the object with ID = 1
  5.    $Person->find(1array('conditions' => "administrator = 1"'order' => "created_on DESC"));

Examples for find first:

  1.    $Person->find('first')// returns the first object fetched by SELECT * FROM people
  2.    $Person->find('first'array('conditions' => array("user_name = ':user_name'"':user_name' => $user_name)));
  3.    $Person->find('first'array('order' => "created_on DESC"'offset' => 5));

Examples for find all:

  1.    $Person->find('all')// returns an array of objects for all the rows fetched by SELECT * FROM people
  2.    $Person->find()// Same as $Person->find('all');
  3.    $Person->find('all'array('conditions' => array("category IN (categories)"'categories' => join(','$categories))'limit' => 50));
  4.    $Person->find('all'array('offset' => 10'limit' => 10));
  5.    $Person->find('all'array('include' => array('account''friends'));

Info

Method findAll (line 1117)

void &findAll( )

Info

Method findAllBy (line 1178)

void &findAllBy( )

Info

Method findBy (line 1197)

void &findBy( )

This method allows you to use finders in a more flexible way like:

findBy('username AND password', $username, $password); findBy('age > ? AND name:contains', 18, 'Joe'); findBy('is_active = true AND session_id', session_id());

Info

Method findBySql (line 1133)

void &findBySql( $sql, [ $limit = null], [ $offset = null], [ $bindings = null])

Works like find_all, but requires a complete SQL string. Examples:

$Post->findBySql("SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id"); $Post->findBySql(array("SELECT * FROM posts WHERE author = ? AND created_on > ?", $author_id, $start_date));

Parameters

  • $sql:
  • $limit:
  • $offset:
  • $bindings:

Info

Method findFirst (line 1107)

void &findFirst( )

Info

Method findFirstBy (line 1154)

void &findFirstBy( )

This function pretends to emulate RoR finders until AkActiveRecord::addMethod becomes stable on future PHP versions.

Info

  • todo - use PHP5 __call method for handling the magic finder methods like findFirstByUnsenameAndPassword('bermi','pass')

Method findLastBy (line 1165)

void &findLastBy( )

Info

Method findOrCreateBy (line 419)

void &findOrCreateBy( )

Info

Method freeze (line 5127)

void freeze( )

Just freeze the attributes hash, such that associations are still accessible even on destroyed records.

Info

  • todo - implement freeze correctly for its intended use

Method get (line 1740)

void get( [ $attribute = null], [ $inspect_for_callback_child_method = true])

Parameters

  • $attribute:
  • $inspect_for_callback_child_method:

Info

Method getAkelosDataType (line 2814)

string getAkelosDataType( &$adodb_column_object)

Akelos data types are mapped to phpAdodb data types

Returns the Akelos data type for an Adodb Column Object

'C'=>'string', // Varchar, capped to 255 characters. 'X' => 'text' // Larger varchar, capped to 4000 characters (to be compatible with Oracle). 'XL' => 'text' // For Oracle, returns CLOB, otherwise the largest varchar size.

'C2' => 'string', // Multibyte varchar 'X2' => 'string', // Multibyte varchar (largest size)

'B' => 'binary', // BLOB (binary large object)

'D' => array('date', 'datetime'), // Date (some databases do not support this, and we return a datetime type) 'T' => array('datetime', 'timestamp'), //Datetime or Timestamp 'L' => 'boolean', // Integer field suitable for storing booleans (0 or 1) 'I' => // Integer (mapped to I4) 'I1' => 'integer', // 1-byte integer 'I2' => 'integer', // 2-byte integer 'I4' => 'integer', // 4-byte integer 'I8' => 'integer', // 8-byte integer 'F' => 'float', // Floating point number 'N' => 'integer' // Numeric or decimal number

Parameters

  • &$adodb_column_object:

Info

  • return - One of this 'string','text','integer','float','datetime','timestamp', 'time', 'name','date', 'binary', 'boolean'

Method getArrayFromAkString (line 4809)

void getArrayFromAkString( $string)

Gets an array from a string.

Acts like Php explode() function but uses any of this as valid separators ' AND ',' and ',' + ',' ',',',';'

Parameters

  • $string:

Info

Method getAttribute (line 1698)

void getAttribute( $attribute, [ $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS])

Parameters

  • $attribute:
  • $inspect_for_callback_child_method:

Info

Method getAttributeBeforeTypeCast (line 3099)

void getAttributeBeforeTypeCast( $attribute)

Parameters

  • $attribute:

Info

Method getAttributeByLocale (line 2989)

void getAttributeByLocale( $attribute, $locale)

Parameters

  • $attribute:
  • $locale:

Info

Method getAttributeCaption (line 1969)

void getAttributeCaption( $attribute)

Parameters

  • $attribute:

Info

Method getAttributeCondition (line 4820)

void getAttributeCondition( $argument)

Parameters

  • $argument:

Info

Method getAttributeLocales (line 2997)

void getAttributeLocales( $attribute)

Parameters

  • $attribute:

Info

Method getAttributeNames (line 2027)

void getAttributeNames( )

Returns an array of names for the attributes available on this object sorted alphabetically.

Info

Method getAttributes (line 1748)

void getAttributes( )

Returns an array of all the attributes with their names as keys and clones of their objects as values in case they are objects.

Info

Method getAttributesBeforeTypeCast (line 3085)

void getAttributesBeforeTypeCast( )

Info

Method getAttributesQuoted (line 3128)

void getAttributesQuoted( $attributes_array)

Parameters

  • $attributes_array:

Info

Method getAvailableAttributes (line 1964)

void getAvailableAttributes( )

Info

Method getAvailableAttributesQuoted (line 3122)

void getAvailableAttributesQuoted( )

Info

Method getAvailableCombinedAttributes (line 2298)

void getAvailableCombinedAttributes( )

Info

Method getAvailableLocales (line 2962)

void getAvailableLocales( )

Info

Method getBaseErrors (line 4258)

void getBaseErrors( )

Returns errors assigned to base object through addToBase according to the normal rules of getErrorsOn($attribute).

Info

Method getClassForDatabaseTableMapping (line 2888)

void getClassForDatabaseTableMapping( )

This method retrieves current class name that will be used to map your database to this object.

Info

Method getColumnNames (line 1995)

void getColumnNames( )

Info

Method getColumns (line 2589)

void getColumns( [ $force_reload = false])

Returns an array of column objects for the table associated with this class.

Parameters

  • $force_reload:

Info

Method getColumnScale (line 3145)

void getColumnScale( $column_name)

Parameters

  • $column_name:

Info

Method getColumnSettings (line 2598)

void getColumnSettings( [ $force_reload = false])

Parameters

  • $force_reload:

Info

Method getColumnsForAttributes (line 2474)

void getColumnsForAttributes( $attributes)

Parameters

  • $attributes:

Info

Method getColumnsWithRegexBoundaries (line 2547)

void getColumnsWithRegexBoundaries( )

Info

Method getColumnType (line 3139)

void getColumnType( $column_name)

Parameters

  • $column_name:

Info

Method getCombinedSubattributes (line 2235)

void getCombinedSubattributes( $attribute)

Parameters

  • $attribute:

Info

Method getConditions (line 1406)

void getConditions( $conditions, [ $prefix = ''], [ $model_name = null])

This functions is used to get the conditions from an AkRequest object

Parameters

  • $conditions:
  • $prefix:
  • $model_name:

Info

Method getConnection (line 2361)

void &getConnection( )

Returns the connection currently associated with the class. This can also be used to "borrow" the connection to do database work unrelated to any of the specific Active Records.

Info

Method getContentColumns (line 2011)

void getContentColumns( )

Returns an array of columns objects where the primary id, all columns ending in "_id" or "_count", and columns used for single table inheritance has been removed.

Info

Method getCurrentLocale (line 2975)

void getCurrentLocale( )

Info

Method getDisplayField (line 2909)

void getDisplayField( )

Info

Method getErrors (line 4239)

void getErrors( )

Returns the Errors array that holds all information about attribute error messages.

Info

Method getErrorsOn (line 4344)

void getErrorsOn( $attribute)

Returns false, if no errors are associated with the specified $attribute.

Returns the error message, if one error is associated with the specified $attribute. Returns an array of error messages, if more than one error is associated with the specified $attribute.

Parameters

  • $attribute:

Info

Method getFullErrorMessages (line 4394)

void getFullErrorMessages( )

Returns all the full error messages in an array.

Info

Method getId (line 1773)

void getId( )

Overrides : AkAssociatedActiveRecord::getId() parent method not documented

Every Active Record class must use "id" as their primary ID. This getter overwrites the native id method, which isn't being used in this context.

Info

Method getInheritanceColumn (line 1537)

void getInheritanceColumn( )

Gets the column name for use with single table inheritance. Can be overridden in subclasses.

Info

Method getInternationalizedColumns (line 2939)

void getInternationalizedColumns( )

Info

Method getObservableState (line 4194)

void getObservableState( )

Info

Method getObservers (line 4218)

void &getObservers( )

Register the reference to an object object

Info

Method getOnlyAvailableAttributes (line 2455)

void getOnlyAvailableAttributes( $attributes)

Parameters

  • $attributes:

Info

Method getPrimaryKey (line 1987)

void getPrimaryKey( )

Returns the primary key field.

Info

Method getSanitizedConditionsArray (line 1389)

void getSanitizedConditionsArray( $conditions_array)

Gets a sanitized version of the input array. Each element will be escaped

Parameters

  • $conditions_array:

Info

Method getSerializedAttributes (line 1959)

void getSerializedAttributes( )

Returns an array of all the attributes that have been specified for serialization as keys and the objects as values.

Info

Method getSubclasses (line 1560)

void getSubclasses( )

Info

Method getTableName (line 2406)

void getTableName( [ $modify_for_associations = true])

Parameters

  • $modify_for_associations:

Info

Method getType (line 5140)

void getType( )

Overrides : AkAssociatedActiveRecord::getType() parent method not documented

Alias for getModelName()

Info

Method hasAttribute (line 2054)

boolean hasAttribute( string $attribute)

Returns true if given attribute exists for this Model.

Parameters

  • string $attribute:

Info

Method hasAttributesDefined (line 1977)

void hasAttributesDefined( )

This function is useful in case you need to know if attributes have been assigned to an object.

Info

Method hasBeenModified (line 5117)

void hasBeenModified( )

Info

Method hasColumn (line 2496)

boolean hasColumn( $column, string $name)

Returns true if given attribute exists for this Model.

Parameters

  • string $name: Name of table to look in
  • $column:

Info

Method hasCombinedAttributes (line 2230)

void hasCombinedAttributes( )

Info

Method hasErrors (line 4413)

void hasErrors( )

Returns true if no errors have been added.

Info

Method incrementAndSaveAttribute (line 1874)

void incrementAndSaveAttribute( $attribute)

Increments the attribute and saves the record.

Parameters

  • $attribute:

Info

Method incrementAttribute (line 1863)

void incrementAttribute( $attribute)

Initializes the attribute to zero if null and adds one. Only makes sense for number-based attributes. Returns attribute value.

Parameters

  • $attribute:

Info

Method incrementCounter (line 1827)

void incrementCounter( $counter_name, $id, [ $difference = 1])

Increments the specified counter by one. So $DiscussionBoard->incrementCounter("post_count",

$discussion_board_id); would increment the "post_count" counter on the board responding to $discussion_board_id. This is used for caching aggregate values, so that they doesn't need to be computed every time. Especially important for looping over a collection where each element require a number of aggregate values. Like the $DiscussionBoard that needs to list both the number of posts and comments.

Parameters

  • $counter_name:
  • $id:
  • $difference:

Info

Method init (line 263)

void init( [ $attributes = array()])

Parameters

  • $attributes:

Info

Method initiateAttributeToNull (line 2771)

void initiateAttributeToNull( $attribute)

Parameters

  • $attribute:

Info

Method initiateColumnsToNull (line 2778)

void initiateColumnsToNull( )

Info

Method instantiate (line 1488)

void &instantiate( $record, [ $set_as_new = true])

Finder methods must instantiate through this method to work with the single-table inheritance model and eager loading associations.

that makes it possible to create objects of different types from the same table.

Parameters

  • $record:
  • $set_as_new:

Info

Method isAttributePresent (line 2042)

void isAttributePresent( $attribute)

Returns true if the specified attribute has been set by the user or by a database load and is neither null nor empty?

Parameters

  • $attribute:

Info

Method isBlank (line 3639)

void isBlank( [ $value = null])

Parameters

  • $value:

Info

Method isCombinedAttribute (line 2149)

boolean isCombinedAttribute( string $attribute)

Returns true if given attribute is a combined attribute for this Model.

Parameters

  • string $attribute:

Info

Method isConnected (line 2352)

void isConnected( )

Returns true if a connection that's accessible to this class have already been opened.

Info

Method isFrozen (line 5132)

void isFrozen( )

Info

Method isInvalid (line 4334)

void isInvalid( $attribute)

Returns true if the specified $attribute has errors associated with it.

Parameters

  • $attribute:

Info

Method isLockingEnabled (line 3318)

void isLockingEnabled( )

Active Records support optimistic locking if the field <tt>lock_version</tt> is present. Each update to the record increments the lock_version column and the locking facilities ensure that records instantiated twice will let the last one saved return false on save() if the first was also updated. Example:

$p1 = new Person(1); $p2 = new Person(1);

$p1->first_name = "Michael"; $p1->save();

$p2->first_name = "should fail"; $p2->save(); // Returns false

You're then responsible for dealing with the conflict by checking the return value of save(); and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.

You must ensure that your database schema defaults the lock_version column to 0.

This behavior can be turned off by setting <tt>AkActiveRecord::lock_optimistically = false</tt>.

Info

Method isNewRecord (line 357)

void isNewRecord( )

Returns true if this object hasn't been saved yet that is, a record for the object doesn't exist yet.

Info

Method isValid (line 4023)

void isValid( )

Returns true if no errors were added otherwise false.

Info

Method loadColumnsSettings (line 2607)

void loadColumnsSettings( [ $force_reload = false])

Parameters

  • $force_reload:

Info

Method maximum (line 4905)

void maximum( $column_name, [ $options = array()])

Calculates the maximum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.

$Person->maximum('age');

Parameters

  • $column_name:
  • $options:

Info

Method minimum (line 4895)

void minimum( $column_name, [ $options = array()])

Calculates the minimum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.

$Person->minimum('age');

Parameters

  • $column_name:
  • $options:

Info

Method newRecord (line 324)

void newRecord( $attributes)

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass an array with key names matching the associated table column names).

In both instances, valid attribute keys are determined by the column names of the associated table; hence you can't have attributes that aren't part of the table columns.

Parameters

  • $attributes:

Info

Method notifyObservers (line 4162)

true notifyObservers( [ $method = null])

Calls the $method using the reference to each registered observer.

Parameters

  • $method:

Info

  • return - (this is used internally for triggering observers on default callbacks)

Method objectCache (line 5145)

void &objectCache( )

Info

Method parseAkelosArgs (line 4777)

void parseAkelosArgs( &$args)

Parses an special formated array as a list of keys and values

This function generates an array with values and keys from an array with numeric keys.

This allows to parse an array to a function in the following manner. create('first_name->', 'Bermi', 'last_name->', 'Ferrer'); //Previous code will be the same that create(array('first_name'=>'Bermi', 'last_name'=> 'Ferrer'));

Use this syntax only for quick testings, not for production environments. If the number of arguments varies, the result might be unpredictable.

This function syntax is disabled by default. You need to define('AK_ENABLE_AKELOS_ARGS', true) if you need this functionality.

Parameters

  • &$args:

Info

  • deprecated -

Method quotedId (line 3107)

void quotedId( )

Info

Method reload (line 370)

void reload( )

Reloads the attributes of this object from the database.

Info

Method removeAttributesProtectedFromMassAssignment (line 1930)

void removeAttributesProtectedFromMassAssignment( $attributes)

Parameters

  • $attributes:

Info

Method requiredForCombination (line 2220)

void requiredForCombination( $attribute)

Parameters

  • $attribute:

Info

Method resetColumnInformation (line 2681)

void resetColumnInformation( )

Resets all the cached information about columns, which will cause they to be reloaded on the next request.

Info

Method save (line 537)

void save( [ $validate = true])

- No record exists: Creates a new record with values matching those of the object attributes.

  • A record does exist: Updates the record with values matching those of the object attributes.

Parameters

  • $validate:

Info

Method select (line 4697)

void select( &$source_array)

Selects and filters a search result to include only specified columns

$people_for_select = $People->select($People->find(),'name','email');

Now $people_for_select will hold an array with array ( array ('name' => 'Jose','email' => 'jose@example.com'), array ('name' => 'Alicia','email' => 'alicia@example.com'), array ('name' => 'Hilario','email' => 'hilario@example.com'), array ('name' => 'Bermi','email' => 'bermi@example.com') );

Parameters

  • &$source_array:

Info

Method set (line 1649)

void set( $attribute, [ $value = null], [ $inspect_for_callback_child_method = true], [ $compose_after_set = true])

Parameters

  • $attribute:
  • $value:
  • $inspect_for_callback_child_method:
  • $compose_after_set:

Info

Method setAccessibleAttributes (line 1893)

void setAccessibleAttributes( )

If this macro is used, only those attributed named in it will be accessible for mass-assignment, such as new ModelName($attributes) and $this->attributes($attributes).

This is the more conservative choice for mass-assignment protection. If you'd rather start from an all-open default and restrict attributes as needed, have a look at AkActiveRecord::setProtectedAttributes().

Info

Method setAttribute (line 1600)

void setAttribute( $attribute, $value, [ $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS], [ $compose_after_set = true])

Parameters

  • $attribute:
  • $value:
  • $inspect_for_callback_child_method:
  • $compose_after_set:

Info

Method setAttributeByLocale (line 3008)

void setAttributeByLocale( $attribute, $value, $locale)

Parameters

  • $attribute:
  • $value:
  • $locale:

Info

Method setAttributeLocales (line 3018)

void setAttributeLocales( $attribute, [ $values = array()])

Parameters

  • $attribute:
  • $values:

Info

Method setAttributes (line 1665)

void setAttributes( $attributes, [ $override_attribute_protection = false])

Allows you to set all the attributes at once by passing in an array with keys matching the attribute names (which again matches the column names).

Sensitive attributes can be protected from this form of mass-assignment by using the $this->setProtectedAttributes method. Or you can alternatively specify which attributes can be accessed in with the $this->setAccessibleAttributes method. Then all the attributes not included in that won?t be allowed to be mass-assigned.

Parameters

  • $attributes:
  • $override_attribute_protection:

Info

Method setColumnSettings (line 2643)

void setColumnSettings( $column_name, $column_object)

Parameters

  • $column_name:
  • $column_object:

Info

Method setConnection (line 2369)

void &setConnection( [ $db_adapter = null])

Sets the connection for the class.

Parameters

  • $db_adapter:

Info

Method setDisplayField (line 2914)

void setDisplayField( $attribute_name)

Parameters

  • $attribute_name:

Info

Method setId (line 1679)

void setId( $value)

Parameters

  • $value:

Info

Method setInheritanceColumn (line 1545)

void setInheritanceColumn( $column_name)

Defines the column name for use with single table inheritance. Can be overridden in subclasses.

Parameters

  • $column_name:

Info

Method setObservableState (line 4189)

void setObservableState( $state_message)

Parameters

  • $state_message:

Info

Method setPrimaryKey (line 2396)

void setPrimaryKey( [ $primary_key = 'id'])

Defines the primary key field ? can be overridden in subclasses.

Parameters

  • $primary_key:

Info

Method setProtectedAttributes (line 1924)

void setProtectedAttributes( )

Attributes named in this macro are protected from mass-assignment, such as new ModelName($attributes) and $this->attributes(attributes). Their assignment will simply be ignored. Instead, you can use the direct writer methods to do assignment.

This is meant to protect sensitive attributes to be overwritten by URL/form hackers.

Example:

  1.    class Customer extends ActiveRecord
  2.     {
  3.       function Customer()
  4.       {
  5.           $this->setProtectedAttributes('credit_rating');
  6.       }
  7.     }
  8.  
  9.     $Customer = new Customer('name' => 'David''credit_rating' => 'Excellent');
  10.     $Customer->credit_rating // => null
  11.     $Customer->attributes(array('description' => 'Jolly fellow''credit_rating' => 'Superb'));
  12.     $Customer->credit_rating // => null
  13.  
  14.     $Customer->credit_rating = 'Average'
  15.     $Customer->credit_rating // => 'Average'

Info

Method setSerializeAttribute (line 3115)

void setSerializeAttribute( $attr_name, [ $class_name = null])

Specifies that the attribute by the name of attr_name should be serialized before saving to the database and unserialized after loading from the database. If class_name is specified, the serialized object must be of that class on retrieval, as a new instance of the object will be loaded with serialized values.

Parameters

  • $attr_name:
  • $class_name:

Info

Method setTableName (line 2423)

void setTableName( [ $table_name = null], [ $check_for_existence = AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES], [ $check_mode = false])

Parameters

  • $table_name:
  • $check_for_existence:
  • $check_mode:

Info

Method sum (line 4915)

void sum( $column_name, [ $options = array()])

Calculates the sum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.

$Person->sum('age');

Parameters

  • $column_name:
  • $options:

Info

Method t (line 2934)

void t( $string, [ $array = null])

Parameters

  • $string:
  • $array:

Info

Method toggleAttribute (line 1790)

void toggleAttribute( $attribute)

Turns an attribute that's currently true into false and vice versa. Returns attribute value.

Parameters

  • $attribute:

Info

Method toggleAttributeAndSave (line 1802)

void toggleAttributeAndSave( $attribute)

Toggles the attribute and saves the record.

Parameters

  • $attribute:

Info

Method toJson (line 4740)

void toJson( )

Info

Method toString (line 4568)

void toString( [ $print = false])

Overrides : AkObject::toString() Object-to-string conversion

Parameters

  • $print:

Info

Method toYaml (line 4754)

void toYaml( [array $data = null])

converts to yaml-strings

examples: User::toYaml($users->find('all')); $Bermi->toYaml();

Parameters

  • array $data: of ActiveRecords[optional] $data

Info

Method transactionComplete (line 3454)

void transactionComplete( )

Info

Method transactionFail (line 3459)

void transactionFail( )

Info

Method transactionHasFailed (line 3465)

void transactionHasFailed( )

Info

Method transactionStart (line 3449)

void transactionStart( )

Transaction support for database operations

Transactions are enabled automatically for Active record objects, But you can nest transactions within models. This transactions are nested, and only the outermost will be executed

$User->transactionStart(); $User->create('username'=>'Bermi'); $Members->create('username'=>'Bermi');

if(!checkSomething()){ $User->transactionFail(); }

$User->transactionComplete();

Info

Method typeCondition (line 1579)

void typeCondition( [ $table_alias = null])

Parameters

  • $table_alias:

Info

Method update (line 604)

void update( $id, $attributes)

Finds the record from the passed id, instantly saves it with the passed attributes (if the validation permits it), and returns it. If the save fail under validations, the unsaved object is still returned.

Parameters

  • $id:
  • $attributes:

Info

Method updateAll (line 651)

void updateAll( $updates, [ $conditions = null])

Updates all records with the SET-part of an SQL update statement in updates and returns an integer with the number of rows updates. A subset of the records can be selected by specifying conditions. Example:
  1. $Billing->updateAll("category = 'authorized', approved = 1""author = 'David'");

Important note: Conditions are not sanitized yet so beware of accepting variable conditions when using this function

Parameters

  • $updates:
  • $conditions:

Info

Method updateAttribute (line 625)

void updateAttribute( $name, $value, [ $should_validate = true])

Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.

Parameters

  • $name:
  • $value:
  • $should_validate:

Info

Method updateAttributes (line 636)

void updateAttributes( $attributes, [ $object = null])

Updates all the attributes in from the passed array and saves the record. If the object is invalid, the saving will fail and false will be returned.

Parameters

  • $attributes:
  • $object:

Info

Method validate (line 4111)

void validate( )

Overwrite this method for validation checks on all saves and use addError($field, $message); for invalid attributes.

Info

Method validateOnCreate (line 4118)

void validateOnCreate( )

Overwrite this method for validation checks used only on creation.

Info

Method validateOnUpdate (line 4125)

void validateOnUpdate( )

Overwrite this method for validation checks used only on updates.

Info

Method validatesAcceptanceOf (line 3579)

void validatesAcceptanceOf( accept $attribute_names, [ $message = 'accepted'], [ $accept = 1])

Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:

class Person extends ActiveRecord { function validateOnCreate() { $this->validatesAcceptanceOf('terms_of_service'); $this->validatesAcceptanceOf('eula', "must be abided"); } }

The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed only if terms_of_service is not null.

Parameters

  • accept $attribute_names: 1 Specifies value that is considered accepted. The default value is a string "1", which makes it easy to relate to an HTML checkbox.
  • $message:
  • $accept:

Info

Method validatesAssociated (line 3620)

void validatesAssociated( $attribute_names, [ $message = 'invalid'])

Validates whether the associated object or objects are all valid themselves. Works with any kind of association.

class Book extends ActiveRecord { var $has_many = 'pages'; var $belongs_to = 'library';

function validate(){ $this->validatesAssociated(array('pages', 'library')); } }

Warning: If, after the above definition, you then wrote:

class Page extends ActiveRecord { var $belongs_to = 'book'; function validate(){ $this->validatesAssociated('book'); } }

...this would specify a circular dependency and cause infinite recursion.

NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validatesPresenceOf.

Parameters

  • $attribute_names:
  • $message:

Info

Method validatesConfirmationOf (line 3548)

void validatesConfirmationOf( $attribute_names, [ $message = 'confirmation'])

Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:

Model: class Person extends ActiveRecord { function validate() { $this->validatesConfirmationOf('password'); $this->validatesConfirmationOf('email_address', "should match confirmation"); } }

View: <?=$form_helper->password_field("person", "password"); ?> <?=$form_helper->password_field("person", "password_confirmation"); ?>

The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual. It exists only as an in-memory variable for validating the password. This check is performed only if password_confirmation is not null.

Parameters

  • $attribute_names:
  • $message:

Info

Method validatesExclusionOf (line 3957)

void validatesExclusionOf( $attribute_names, $array_of_possibilities, [ $message = 'exclusion'], [ $allow_null = false])

Validates that the value of the specified attribute is not in a particular array of elements.

class Person extends ActiveRecord { function validate() { $this->validatesExclusionOf('username', array('admin', 'superuser'), "You don't belong here"); $this->validatesExclusionOf('age', range(30,60), "This site is only for under 30 and over 60"); } }

Parameters: <tt>$array_of_possibilities</tt> - An array of items that the value shouldn't be part of <tt>$message</tt> - Specifies a customer error message (default is: "is reserved") <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)

Parameters

  • $attribute_names:
  • $array_of_possibilities:
  • $message:
  • $allow_null:

Info

Method validatesFormatOf (line 3900)

void validatesFormatOf( $attribute_names, $regular_expression, [ $message = 'invalid'], [ $regex_function = 'preg_match'])

Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression provided.

  1.    class Person extends ActiveRecord
  2.    {
  3.        function validate()
  4.        {
  5.            $this->validatesFormatOf('email'"/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/");
  6.        }
  7.    }

A regular expression must be provided or else an exception will be raised.

There are some regular expressions bundled with the Akelos Framework. You can override them by defining them as PHP constants (Ie. define('AK_EMAIL_REGULAR_EXPRESSION', '/^My custom email regex$/');). This must be done on your main configuration file. This are predefined perl-like regular extensions.

* AK_NOT_EMPTY_REGULAR_EXPRESSION ---> /.+/ * AK_EMAIL_REGULAR_EXPRESSION ---> /^([a-z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-z0-9\-]+\.)+))([a-z]{2,4}|[0-9]{1,3})(\]?)$/i * AK_NUMBER_REGULAR_EXPRESSION ---> /^[0-9]+$/ * AK_PHONE_REGULAR_EXPRESSION ---> /^([\+]?[(]?[\+]?[ ]?[0-9]{2,3}[)]?[ ]?)?[0-9 ()\-]{4,25}$/ * AK_DATE_REGULAR_EXPRESSION ---> /^(([0-9]{1,2}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{2,4})|([0-9]{2,4}(\-|\/|\.| )[0-9]{1,2}(\-|\/|\.| )[0-9]{1,2})){1}$/ * AK_IP4_REGULAR_EXPRESSION ---> /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/ * AK_POST_CODE_REGULAR_EXPRESSION ---> /^[0-9A-Za-z -]{2,7}$/

IMPORTANT: Predefined regular expressions may change in newer versions of the Framework, so is highly recommended to hardcode you own on regex on your validators.

Params: <tt>$message</tt> - A custom error message (default is: "is invalid") <tt>$regular_expression</tt> - The regular expression used to validate the format with (note: must be supplied!)

Parameters

  • $attribute_names:
  • $regular_expression:
  • $message:
  • $regex_function:

Info

Method validatesInclusionOf (line 3928)

void validatesInclusionOf( $attribute_names, $array_of_possibilities, [ $message = 'inclusion'], [ $allow_null = false])

Validates whether the value of the specified attribute is available in a particular array of elements.

class Person extends ActiveRecord { function validate() { $this->validatesInclusionOf('gender', array('male', 'female'), "woah! what are you then!??!!"); $this->validatesInclusionOf('age', range(0, 99)); }

Parameters: <tt>$array_of_ possibilities</tt> - An array of available items <tt>$message</tt> - Specifies a customer error message (default is: "is not included in the list") <tt>$allow_null</tt> - If set to true, skips this validation if the attribute is null (default is: false)

Parameters

  • $attribute_names:
  • $array_of_possibilities:
  • $message:
  • $allow_null:

Info

Method validatesLengthOf (line 3688)

void validatesLengthOf( $attribute_names, [ $options = array()])

Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:

class Person extends ActiveRecord { function validate() { $this->validatesLengthOf('first_name', array('maximum'=>30)); $this->validatesLengthOf('last_name', array('maximum'=>30,'message'=> "less than %d if you don't mind")); $this->validatesLengthOf('last_name', array('within'=>array(7, 32))); $this->validatesLengthOf('last_name', array('in'=>array(6, 20), 'too_long' => "pick a shorter name", 'too_short' => "pick a longer name")); $this->validatesLengthOf('fav_bra_size', array('minimum'=>1, 'too_short'=>"please enter at least %d character")); $this->validatesLengthOf('smurf_leader', array('is'=>4, 'message'=>"papa is spelled with %d characters... don't play me.")); } }

NOTE: Be aware that $this->validatesLengthOf('field', array('is'=>5)); Will match a string containing 5 characters (Ie. "Spain"), an integer 5, and an array with 5 elements. You must supply additional checking to check for appropriate types.

Configuration options: <tt>minimum</tt> - The minimum size of the attribute <tt>maximum</tt> - The maximum size of the attribute <tt>is</tt> - The exact size of the attribute <tt>within</tt> - A range specifying the minimum and maximum size of the attribute <tt>in</tt> - A synonym(or alias) for :within <tt>allow_null</tt> - Attribute may be null; skip validation.

<tt>too_long</tt> - The error message if the attribute goes over the maximum (default "is" "is too long (max is %d characters)") <tt>too_short</tt> - The error message if the attribute goes under the minimum (default "is" "is too short (min is %d characters)") <tt>wrong_length</tt> - The error message if using the "is" method and the attribute is the wrong size (default "is" "is the wrong length (should be %d characters)") <tt>message</tt> - The error message to use for a "minimum", "maximum", or "is" violation. An alias of the appropriate too_long/too_short/wrong_length message

Parameters

  • $attribute_names:
  • $options:

Info

Method validatesNumericalityOf (line 3989)

void validatesNumericalityOf( $attribute_names, [ $message = 'not_a_number'], [ $only_integer = false], [ $allow_null = false])

Validates whether the value of the specified attribute is numeric.

class Person extends ActiveRecord { function validate() { $this->validatesNumericalityOf('value'); } }

Parameters: <tt>$message</tt> - A custom error message (default is: "is not a number") <tt>$only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) <tt>$allow_null</tt> Skip validation if attribute is null (default is false).

Parameters

  • $attribute_names:
  • $message:
  • $only_integer:
  • $allow_null:

Info

Method validatesPresenceOf (line 3647)

void validatesPresenceOf( $attribute_names, [ $message = 'blank'])

Validates that the specified attributes are not blank (as defined by AkActiveRecord::isBlank()).

Parameters

  • $attribute_names:
  • $message:

Info

Method validatesSizeOf (line 3771)

void validatesSizeOf( $attribute_names, [ $options = array()])

Parameters

  • $attribute_names:
  • $options:

Info

Method validatesUniquenessOf (line 3813)

void validatesUniquenessOf( $attribute_names, [ $options = array()])

Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user can be named "davidhh".

class Person extends ActiveRecord { function validate() { $this->validatesUniquenessOf('passport_number'); $this->validatesUniquenessOf('user_name', array('scope' => "account_id")); } }

It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.

class TeacherSchedule extends ActiveRecord { function validate() { $this->validatesUniquenessOf('passport_number'); $this->validatesUniquenessOf('teacher_id', array('scope' => array("semester_id", "class_id")); } }

When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.

Configuration options: <tt>message</tt> - Specifies a custom error message (default is: "has already been taken") <tt>scope</tt> - Ensures that the uniqueness is restricted to a condition of "scope = record.scope" <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default). <tt>if</tt> - Specifies a method to call or a string to evaluate to determine if the validation should occur (e.g. 'if' => 'allowValidation', or 'if' => '$this->signup_step > 2'). The method, or string should return or evaluate to a true or false value.

Parameters

  • $attribute_names:
  • $options:

Info

Method yieldEachError (line 4360)

void yieldEachError( )

Yields each attribute and associated message per error added.

Info

Method yieldEachFullError (line 4382)

void yieldEachFullError( )

Yields each full error message added. So Person->addError("first_name", "can't be empty") will be returned through iteration as "First name can't be empty".

Info

Method yieldError (line 4369)

void yieldError( $message)

Parameters

  • $message:

Info

Method _destroy (line 797)

void _destroy( )

Info

Method _extractConditionsFromArgs (line 1042)

void _extractConditionsFromArgs( $args, $options)

Parameters

  • $args:
  • $options:

Info

Method _extractOptionsFromArgs (line 1022)

void _extractOptionsFromArgs( &$args)

Parameters

  • &$args:

Info

Method _extractValueFromDefault (line 5167)

void _extractValueFromDefault( $default)

Parameters

  • $default:

Info

Method _findEvery (line 957)

void &_findEvery( $options)

Parameters

  • $options:

Info

Method _findFromIds (line 982)

void &_findFromIds( $ids, $options)

Parameters

  • $ids:
  • $options:

Info

Method _findInitial (line 939)

void &_findInitial( $options)

Parameters

  • $options:

Info

Method _getFindBySqlAndColumns (line 1256)

void _getFindBySqlAndColumns( $find_by_sql, &$query_values)

Parameters

  • $find_by_sql:
  • &$query_values:

Info

Method _getVariableSqlCondition (line 1334)

string _getVariableSqlCondition( $variable_condition)

Given a condition that uses bindings like "user = ? AND created_at > ?" will return a string replacing the "?" bindings with the column values for current Active Record

Parameters

  • $variable_condition:

Info

Method _isOptionsHash (line 1028)

void _isOptionsHash( $options)

Parameters

  • $options:

Info

Method _sanitizeConditionsVariables (line 1079)

void _sanitizeConditionsVariables( &$options)

Parameters

  • &$options:

Info

Method _setRecordTimestamps (line 495)

void _setRecordTimestamps( )

Info

Method _validateFindOptions (line 1099)

void _validateFindOptions( &$options)

Parameters

  • &$options:

Info

Inherited Variables

Inherited Class Variable Summary

Inherited From Class AkAssociatedActiveRecord

AkAssociatedActiveRecord::$_AssociationHandler -

AkAssociatedActiveRecord::$_associationId -

AkAssociatedActiveRecord::$_associationIds -

Inherited From Class AkBaseModel

AkBaseModel::$_modelName -

Inherited Methods

Inherited Method Summary

Inherited From Class AkAssociatedActiveRecord

AkAssociatedActiveRecord::assign() -

AkAssociatedActiveRecord::build() - Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key but has not yet been saved.

AkAssociatedActiveRecord::constructFinderSqlWithAssociations() - Used for generating custom selections for habtm, has_many and has_one queries

AkAssociatedActiveRecord::constructSql() -

AkAssociatedActiveRecord::constructSqlForInclusion() -

AkAssociatedActiveRecord::create() -

AkAssociatedActiveRecord::find() -

AkAssociatedActiveRecord::findWithAssociations() -

AkAssociatedActiveRecord::getAssociated() - Gets an array of associated object of selected association type.

AkAssociatedActiveRecord::getAssociatedFinderSqlOptions() -

AkAssociatedActiveRecord::getAssociatedHandlerName() -

AkAssociatedActiveRecord::getAssociatedIds() -

AkAssociatedActiveRecord::getAssociatedType() -

AkAssociatedActiveRecord::getAssociationId() -

AkAssociatedActiveRecord::getAssociationOption() -

AkAssociatedActiveRecord::getAssociationType() -

AkAssociatedActiveRecord::getCollectionHandlerName() -

AkAssociatedActiveRecord::getId() -

AkAssociatedActiveRecord::getType() -

AkAssociatedActiveRecord::hasAssociations() -

AkAssociatedActiveRecord::load() -

AkAssociatedActiveRecord::loadAssociations() -

AkAssociatedActiveRecord::replace() -

AkAssociatedActiveRecord::setAssociationHandler() -

AkAssociatedActiveRecord::setAssociationOption() -

AkAssociatedActiveRecord::_addTableAliasesToAssociatedSql() -

AkAssociatedActiveRecord::_findBySqlWithAssociations() -

AkAssociatedActiveRecord::_loadAssociationHandler() -


Inherited From Class AkBaseModel

AkBaseModel::getModelName() - Returns current model name

AkBaseModel::getParentModelName() -

AkBaseModel::setModelName() - Sets current model name

AkBaseModel::setParentModelName() -

AkBaseModel::_getIncludedModelNames() -

AkBaseModel::_getModelName() - This method will nicely handle model names even on


Inherited From Class AkObject

AkObject::AkObject() - A hack to support __construct() on PHP 4

AkObject::__construct() - Class constructor, overriden in descendant classes

AkObject::freeMemory() - Unsets circular reference children that are not freed from memory when calling unset() or when the parent object is garbage collected.

AkObject::log() -

AkObject::toString() - Object-to-string conversion

AkObject::__clone() - Clone class (Zend Engine 2 compatibility trick)

AkObject::__destruct() - Class destructor, overriden in descendant classes

AkObject::__toString() -



Documentation generated on Tue, 17 Jun 2008 14:24:02 +0200 by phpDocumentor 1.3.2