## Class TActiveRecord

Description

Base class for active records.

An active record creates an object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

Active record objects are stateful, this is main difference between the TActiveRecord implementation and the TTableGateway implementation.

The essence of an Active Record is an object model of the domain (e.g. products, items) that incorporates both behavior and data in which the classes match very closely the record structure of an underlying database. Each Active Record is responsible for saving and loading to the database and also for any domain logic that acts on the data.

The Active Record provides methods that do the following:

1. Construct an instance of the Active Record from a SQL result set row.
2. Construct a new instance for later insertion into the table.
3. Finder methods to wrap commonly used SQL queries and return Active Record objects.
4. Update the database and insert into it the data in the Active Record.

Example:

     class UserRecord extends TActiveRecord
     {
         const TABLE='users'; //optional table name.

         public $username; //corresponds to the fieldname in the table
              public $email;

         //returns active record finder instance
              public static function finder($className=__CLASS__)
         {
             return parent::finder($className);
         }
     }

     //create a connection and give it to the ActiveRecord manager.
      $dsn = 'pgsql:host=localhost;dbname=test';
     $conn = new TDbConnection($dsn, 'dbuser','dbpass');
     TActiveRecordManager::getInstance()->setDbConnection($conn);

     //load the user record with username (primary key) 'admin'.
      $user = UserRecord::finder()->findByPk('admin');
     $user->email = 'admin@example.org';
     $user->save(); //update the 'admin' record.

Since v3.1.1, TActiveRecord starts to support column mapping. The physical column names (defined in database) can be mapped to logical column names (defined in active classes as public properties.) To use this feature, declare a static class variable COLUMN_MAPPING like the following:

     class UserRecord extends TActiveRecord
     {
         const TABLE='users';
         public static $COLUMN_MAPPING=array
         (
             'user_id'=>'username',
             'email_address'=>'email',
         );
         public $username;
         pulbic $email;
     }

In the above, the 'users' table consists of 'user_id' and 'email_address' columns, while the UserRecord class declares 'username' and 'email' properties. By using column mapping, we can regularize the naming convention of column names in active record.

- abstract:
- since: 3.1
- version: $Id: TActiveRecord.php 2274 2007-09-29 22:07:12Z xue $
- author: Wei Zhuo <weizho[at]gmail[dot]com>

Located in /Data/ActiveRecord/TActiveRecord.php (line 95)

    TComponent
       |
       --TActiveRecord

Class Constant Summary
BELONGS_TO = 'BELONGS_TO'
HAS_MANY = 'HAS_MANY'
HAS_ONE = 'HAS_ONE'
Variable Summary
array $COLUMN_MAPPING
array $RELATIONS
Method Summary
TActiveRecord __construct ([array $data = array()], [TDbConnection $connection = null])
array collectObjects (TDbDataReader $reader)
boolean commitChanges ()
TActiveRecord copyFrom (mixed $data)
int count ([string|TActiveRecordCriteria $criteria = null], [mixed $parameters = array()])
boolean delete ()
int deleteAll ([string|TActiveRecordCriteria $criteria = null], [mixed $parameters = array()])
void deleteAllByPks (mixed $keys)
int deleteByPk (mixed $keys)
boolean equals (TActiveRecord $record, [boolean $strict = false])
TActiveRecord find (string|TActiveRecordCriteria $criteria, [mixed $parameters = array()])
array findAll ([string|TActiveRecordCriteria $criteria = null], [mixed $parameters = array()])
array findAllByIndex (TActiveRecordCriteria $criteria, array $fields, array $values)
array findAllByPks (mixed $keys)
array findAllBySql (string $sql, [array $parameters = array()])
TActiveRecord findByPk (mixed $keys)
TActiveRecord findBySql (string $sql, [array $parameters = array()])
TActiveRecord finder ([string $className = __CLASS__])
mixed getColumnValue (string $columnName)
TSqlCriteria getCriteria (string|TSqlCriteria $criteria, mixed $parameters, [array $args = array()])
TDbConnection getDbConnection ()
TActiveRecordGateway getRecordGateway ()
TActiveRecordManager getRecordManager ()
TActiveRecordRelation getRelationHandler (string $property, array $args)
void onCreateCommand (TDataGatewayEventParameter $param)
void onExecuteCommand (TDataGatewayResultEventParameter $param)
TActiveRecord populateObject (string $type, array $data)
boolean save ()
void setColumnValue (string $columnName, mixed $value)
void setDbConnection (TDbConnection $connection)
mixed __call (mixed $method, mixed $args)
void __sleep ()
void __wake ()
Variables
array $COLUMN_MAPPING = array() (line 111)

This static variable defines the column mapping.

The keys are physical column names as defined in database, and the values are logical column names as defined as public variable/property names for the corresponding active record class.

- var: column mapping. Keys: physical column names, values: logical column names.
- static:
- access: public
- since: 3.1.1

array $RELATIONS = array() (line 120)

This static variable defines the relationships.

The keys are public variable/property names defined in the AR class. Each value is an array, e.g. array(self::HAS_MANY, 'PlayerRecord').

- var: relationship.
- static:
- access: public
- since: 3.1.1

Methods
Constructor __construct (line 155)

Create a new instance of an active record with given $data. The record can be saved to the database specified by the $connection object.

- access: public

TActiveRecord __construct ([array $data = array()], [TDbConnection $connection = null])

- array $data: optional name value pair record data.
- TDbConnection $connection: optional database connection this object record use.

collectObjects (line 404)

- access: protected

array collectObjects (TDbDataReader $reader)

- TDbDataReader $reader: data reader

commitChanges (line 299)

Commit changes to the record, may insert, update or delete depending on the record state given in TObjectStateRegistery.

- return: true if changes were made.
- access: protected

boolean commitChanges ()
copyFrom (line 181)

Copies data from an array or another object.

- return: current instance.
- access: public
- throws: TActiveRecordException if data is not array or not object.

TActiveRecord copyFrom (mixed $data)
count (line 555)

Find the number of records.

- return: number of records.
- access: public

int count ([string|TActiveRecordCriteria $criteria = null], [mixed $parameters = array()])

- string|TActiveRecordCriteria $criteria: SQL condition or criteria object.
- mixed $parameters: parameter values.

delete (line 315)

Deletes the current record from the database. Once deleted, this object can not be saved again in the same instance.

- return: true if the record was deleted successfully, false otherwise.
- access: public

boolean delete ()
deleteAll (line 367)

Delete multiple records using a criteria.

- return: number of records deleted.
- access: public

int deleteAll ([string|TActiveRecordCriteria $criteria = null], [mixed $parameters = array()])

- string|TActiveRecordCriteria $criteria: SQL condition or criteria object.
- mixed $parameters: parameter values.

deleteAllByPks (line 355)

Alias for deleteByPk()

- access: public

void deleteAllByPks (mixed $keys)
deleteByPk (line 345)

Delete records by primary key. Usage:

     $finder->deleteByPk($primaryKey); //delete 1 record
      $finder->deleteByPk($key1,$key2,...); //delete multiple records
      $finder->deleteByPk(array($key1,$key2,...)); //delete multiple records

For composite primary keys (determined from the table definitions):

     $finder->deleteByPk(array($key1,$key2)); //delete 1 record

     //delete multiple records
      $finder->deleteByPk(array($key1,$key2), array($key3,$key4),...);

     //delete multiple records
      $finder->deleteByPk(array( array($key1,$key2), array($key3,$key4), .. ));

- return: number of records deleted.
- access: public

int deleteByPk (mixed $keys)

- mixed $keys: primary key values.

equals (line 221)

Compare two records using their primary key values (all column values if table does not defined primary keys). The default uses simple == for comparison of their values. Set $strict=true for identity comparison.

- return: true if $record equals, false otherwise.
- access: public

boolean equals (TActiveRecord $record, [boolean $strict = false])

- TActiveRecord $record: another record to compare with.
- boolean $strict: true to perform strict identity comparison

find (line 430)

Find one single record that matches the criteria.

Usage:

     $finder->find('username = :name AND password = :pass',
                         array(':name'=>$name, ':pass'=>$pass));
     $finder->find('username = ? AND password = ?', array($name, $pass));
     $finder->find('username = ? AND password = ?', $name, $pass);
     //$criteria is of TActiveRecordCriteria
      $finder->find($criteria); //the 2nd parameter for find() is ignored.

- return: matching record object.
- access: public

TActiveRecord find (string|TActiveRecordCriteria $criteria, [mixed $parameters = array()])

- string|TActiveRecordCriteria $criteria: SQL condition or criteria object.
- mixed $parameters: parameter values.

findAll (line 445)

Same as find() but returns an array of objects.

- return: matching record objects
- access: public

array findAll ([string|TActiveRecordCriteria $criteria = null], [mixed $parameters = array()])

- string|TActiveRecordCriteria $criteria: SQL condition or criteria object.
- mixed $parameters: parameter values.

findAllByIndex (line 543)

Fetches records using the sql clause "(fields) IN (values)", where fields is an array of column names and values is an array of values that the columns must have.

This method is to be used by the relationship handler.

- return: matching active records.
- access: public

array findAllByIndex (TActiveRecordCriteria $criteria, array $fields, array $values)

- TActiveRecordCriteria $criteria: additional criteria
- array $fields: field names to match with "(fields) IN (values)" sql clause.
- array $values: matching field values.

findAllByPks (line 491)

Find multiple records matching a list of primary or composite keys.

For scalar primary keys:

     $finder->findAllByPk($key1, $key2, ...);
     $finder->findAllByPk(array($key1, $key2, ...));

For composite keys:

     $finder->findAllByPk(array($key1, $key2), array($key3, $key4), ...);
     $finder->findAllByPk(array(array($key1, $key2), array($key3, $key4), ...));

- return: matching ActiveRecords
- access: public

array findAllByPks (mixed $keys)

- mixed $keys: primary keys

findAllBySql (line 523)

Find records using full SQL, returns corresponding record object.

The names of the column retrieved must be defined in your Active Record class.

- return: matching active records.
- access: public

array findAllBySql (string $sql, [array $parameters = array()])

- array $parameters
- string $sql: select SQL

findByPk (line 466)

Find one record using only the primary key or composite primary keys. Usage:

     $finder->findByPk($primaryKey);
     $finder->findByPk($key1, $key2, ...);
     $finder->findByPk(array($key1,$key2,...));

- access: public

TActiveRecord findByPk (mixed $keys)

- mixed $keys: primary keys

findBySql (line 507)

Find records using full SQL, returns corresponding record object.

The names of the column retrieved must be defined in your Active Record class.

- access: public

TActiveRecord findBySql (string $sql, [array $parameters = array()])

- array $parameters
- string $sql: select SQL

finder (line 252)

Returns the instance of a active record finder for a particular class.

The finder objects are static instances for each ActiveRecord class. This means that event handlers bound to these finder instances are class wide. Create a new instance of the ActiveRecord class if you wish to bound the event handlers to object instance.

- return: active record finder instance.
- static:
- access: public
- throws: TActiveRecordException if class name equals 'TActiveRecord'.

TActiveRecord finder ([string $className = __CLASS__])

- string $className: active record class name.

getColumnValue (line 695)

Retrieves the column value according to column name.

This method is used internally.

- return: the corresponding column value
- access: public
- since: 3.1.1

mixed getColumnValue (string $columnName)

- string $columnName: the column name (as defined in database schema)

getCriteria (line 641)

Create a new TSqlCriteria object from a string $criteria. The $args are additional parameters and are used in place of the $parameters if $parameters is not an array and $args is an arrary.

- return: criteria object.
- access: protected

TSqlCriteria getCriteria (string|TSqlCriteria $criteria, mixed $parameters, [array $args = array()])

- string|TSqlCriteria $criteria: sql criteria
- mixed $parameters: parameters passed by the user.
- array $args: additional parameters obtained from function_get_args().

getDbConnection (line 196)

Gets the current Db connection, the connection object is obtained from the TActiveRecordManager if connection is currently null.

- return: current db connection for this object.
- access: public

TDbConnection getDbConnection ()
getRecordGateway (line 280)

- return: record table gateway.
- access: public

TActiveRecordGateway getRecordGateway ()
getRecordManager (line 272)

Gets the record manager for this object, the default is to call TActiveRecordManager::getInstance().

- return: default active record manager.
- access: public

TActiveRecordManager getRecordManager ()
getRelationHandler (line 570)

Returns the active record relationship handler for $RELATION with key value equal to the $property value.

- access: protected

TActiveRecordRelation getRelationHandler (string $property, array $args)

- string $property: relationship property name.
- array $args: method call arguments.

onCreateCommand (line 666)

Raised when a command is prepared and parameter binding is completed.

The parameter object is TDataGatewayEventParameter of which the TDataGatewayEventParameter::getCommand property can be inspected to obtain the sql query to be executed.

Note well that the finder objects obtained from ActiveRecord::finder() method are static objects. This means that the event handlers are bound to a static finder object and not to each distinct active record object.

- access: public

void onCreateCommand (TDataGatewayEventParameter $param)

- TDataGatewayEventParameter $param

onExecuteCommand (line 683)

Raised when a command is executed and the result from the database was returned.

The parameter object is TDataGatewayResultEventParameter of which the TDataGatewayEventParameter::getResult property contains the data return from the database. The data returned can be changed by setting the TDataGatewayEventParameter::setResult property.

Note well that the finder objects obtained from ActiveRecord::finder() method are static objects. This means that the event handlers are bound to a static finder object and not to each distinct active record object.

- access: public

void onExecuteCommand (TDataGatewayResultEventParameter $param)

- TDataGatewayResultEventParameter $param

populateObject (line 380)

Populate the record with data, registers the object as clean.

- return: object record, null if data is empty.
- access: protected

TActiveRecord populateObject (string $type, array $data)

- string $type: new record name
- array $data: name value pair record data

save (line 289)

Saves the current record to the database, insert or update is automatically determined.

- return: true if record was saved successfully, false otherwise.
- access: public

boolean save ()
setColumnValue (line 710)

Sets the column value according to column name.

This method is used internally.

- access: public
- since: 3.1.1

void setColumnValue (string $columnName, mixed $value)

- string $columnName: the column name (as defined in database schema)
- mixed $value: the corresponding column value

setDbConnection (line 208)

- access: public

void setDbConnection (TDbConnection $connection)

- TDbConnection $connection: db connection object for this record.

__call (line 606)

Dynamic find method using parts of method name as search criteria.

Method name starting with "findBy" only returns 1 record. Method name starting with "findAllBy" returns 0 or more records. Method name starting with "deleteBy" deletes records by the trail criteria. The condition is taken as part of the method name after "findBy", "findAllBy" or "deleteBy".

The following are equivalent:

     $finder->findByName($name)
     $finder->find('Name = ?', $name);

     $finder->findByUsernameAndPassword($name,$pass); // OR may be used
      $finder->findBy_Username_And_Password($name,$pass); // _OR_ may be used
      $finder->find('Username = ? AND Password = ?', $name, $pass);

     $finder->findAllByAge($age);
     $finder->findAll('Age = ?', $age);

     $finder->deleteAll('Name = ?', $name);
     $finder->deleteByName($name);

- return: single record if method name starts with "findBy", 0 or more records if method name starts with "findAllBy"
- access: public

mixed __call (mixed $method, mixed $args)
__sleep (line 135)

Prevent __call() method creating __sleep() when serializing.

- access: public

void __sleep ()
__wake (line 143)

Prevent __call() method creating __wake() when unserializing.

- access: public

void __wake ()

#### Inherited Methods

Inherited From TComponent

> TComponent::addParsedObject()
> TComponent::attachEventHandler()
> TComponent::canGetProperty()
> TComponent::canSetProperty()
> TComponent::createdOnTemplate()
> TComponent::detachEventHandler()
> TComponent::evaluateExpression()
> TComponent::evaluateStatements()
> TComponent::getEventHandlers()
> TComponent::getSubProperty()
> TComponent::hasEvent()
> TComponent::hasEventHandler()
> TComponent::hasProperty()
> TComponent::raiseEvent()
> TComponent::setSubProperty()
> TComponent::__get()
> TComponent::__set()

Class Constants
BELONGS_TO = 'BELONGS_TO' (line 98)
HAS_MANY = 'HAS_MANY' (line 97)
HAS_ONE = 'HAS_ONE' (line 99)

Documentation generated on Sun, 30 Sep 2007 19:10:17 -0400 by phpDocumentor 1.3.0RC4