Active Record

Active Records are objects that wrap a row in a database table or view, encapsulates the database access and adds domain logic on that data. The basics of an Active Record is a business object class, e.g., a Products class, that match very closely the record structure of an underlying database table. Each Active Record will be responsible for saving and loading data to and from the database.

Info: The data structure of an Active Record should match exactly that of a table in the database. Each field in the class must correspond to one column in the table.

When to Use It

Active Record is a good choice for domain logic that isn't too complex, such as creates, reads, updates, and deletes. Derivations and validations based on a single record work well in this structure. Active Record has the primary advantage of simplicity. It's easy to build Active Records, and they are easy to understand.

However, as your business logic grows in complexity, you'll soon want to use your object's direct relationships, collections, inheritance, and so forth. These don't map easily onto Active Record, and adding them piecemeal gets very messy. Another argument against Active Record is the fact that it couples the object design to the database design. This makes it more difficult to refactor as a project goes forward.

The alternative is to use a Data Mapper that separates the roles of the business object and how these objects are stored. Prado provides a complimentary choice between Active Record and SqlMap Data Mapper. A SqlMap Data Mapper can be used to load Active Record objects, in turn, these Active Record objects can be used to update the database. The "relationship" between Active Records and SqlMap is illustrated in the following diagram. More details regarding the SqlMap Data Mapper can be found in the SqlMap Manual. alt="Active Records and SqlMap DataMapper" id="fig:diagram.png" class="figure"/>

The Active Record class has methods that do the following:

Database Supported

The Active Record implementation utilizes the Prado DAO classes for data access. The current Active Record implementation supports the following database.

Support for other databases can be provided when there are sufficient demand.

Defining an Active Record

Let us consider the following "users" table that contains two columns named "username" and "email", where "username" is also the primary key. CREATE TABLE users ( username VARCHAR( 20 ) NOT NULL , email VARCHAR( 200 ) , PRIMARY KEY ( username ) );

Next we define our Active Record class that corresponds to the "users" table. class UserRecord extends TActiveRecord { const TABLE='users'; //table name public $username; //the column named "username" in the "users" table public $email; /** * @return TActiveRecord active record finder instance */ public static function finder($className=__CLASS__) { return parent::finder($className); } }

Each property of the UserRecord class must correspond to a column with the same name in the "users" table. The class constant TABLE is optional when the class name is the same as the table name in the database, otherwise TABLE must specify the table name that corresponds to your Active Record class.

Tip: You may specify qualified table names. E.g. for MySQL, TABLE = "`database1`.`table1`".

Since TActiveRecord extends TComponent, setter and getter methods can be defined to allow control over how variables are set and returned. For example, adding a $level property to the UserRecord class:

class UserRecord extends TActiveRecord { ... //existing definitions as above private $_level; public function setLevel($value) { $this->_level=TPropertyValue::ensureInteger($value,0); } public function getLevel($value){ return $this->_level; } }
Info: TActiveRecord can also work with database views by specifying the constant TABLE corresponding to the view name. However, objects returned from views are read-only, calling the save() or delete() method will raise an exception.

The static method finder() returns an UserRecord instance that can be used to load records from the database. The loading of records using the finer methods is discuss a little later. The TActiveRecord::finder() static method takes the name of the current Active Record class as parameter.

Setting up a database connection

A default database connection for Active Record can be set as follows. See Establishing Database Connection for futher details regarding creation of database connection in general. //create a connection and give it to the Active Record manager. $dsn = 'pgsql:host=localhost;dbname=test'; //Postgres SQL $conn = new TDbConnection($dsn, 'dbuser','dbpass'); TActiveRecordManager::getInstance()->setDbConnection($conn);

The default database connection can also be configured using a <module> tag in the application.xml or config.xml as follows.

Tip: The EnableCache attribute when set to "true" will cache the table meta data, that is, the table columns names, indexes and constraints are saved in the cache and reused. You must clear or disable the cache if you wish to see chanages made to your table definitions. A cache module must also be defined for the cache to function.

A ConnectionID property can be specified with value corresponding to another TDataSourceConfig module configuration's ID value. This allows the same database connection to be used in other modules such as SqlMap.

Loading data from the database

The TActiveRecord class provides many convenient methods to find records from the database. The simplest is finding records by matching primary keys. See the for more details.

findByPk()

Finds one record using only the primary key or composite primary keys. $finder = UserRecord::finder(); $user = $finder->findByPk($primaryKey); //when the table uses composite keys $record = $finder->findByPk($key1, $key2, ...); $record = $finder->findByPk(array($key1, $key2,...));

findAllByPks()

Finds multiple records using a list of primary keys or composite primary keys. The following are equivalent for scalar primary keys (primary key consisting of only one column/field). $finder = UserRecord::finder(); $users = $finder->findAllByPk($key1, $key2, ...); $users = $finder->findAllByPk(array($key1, $key2, ...)); The following are equivalent for composite keys. //when the table uses composite keys $record = $finder->findAllByPks(array($key1, $key2), array($key3, $key4), ...); $keys = array( array($key1, $key2), array($key3, $key4), ... ); $record = $finder->findAllByPks($keys);

find()

Finds one single record that matches the criteria. The criteria can be a partial SQL string or a TActiveRecordCriteria object.

$finder = UserRecord::finder(); //:name and :pass are place holders for specific values of $name and $pass $finder->find('username = :name AND password = :pass', array(':name'=>$name, ':pass'=>$pass)); //using position place holders $finder->find('username = ? AND password = ?', array($name, $pass)); //same as above $finder->find('username = ? AND password = ?', $name, $pass); //$criteria is of TActiveRecordCriteria $finder->find($criteria); //the 2nd parameter for find() is ignored.

The TActiveRecordCriteria class has the following properties:

$criteria = new TActiveRecordCriteria; $criteria->Condition = 'username = :name AND password = :pass'; $criteria->Parameters[':name'] = 'admin'; $criteria->Parameters[':pass'] = 'prado'; $criteria->OrdersBy['level'] = 'desc'; $criteria->OrdersBy['name'] = 'asc'; $criteria->Limit = 10; $criteria->Offset = 20;

findAll()

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

findBy*() and findAllBy*()

Dynamic find method using parts of method name as search criteria. Method names starting with findBy return 1 record only. Method names starting with findAllBy return an array of records. The condition is taken as part of the method name after findBy or findAllBy. The following blocks of code are equivalent:

$finder->findByName($name) $finder->find('Name = ?', $name); $finder->findByUsernameAndPassword($name,$pass); $finder->findBy_Username_And_Password($name,$pass); $finder->find('Username = ? AND Password = ?', $name, $pass); $finder->findAllByAge($age); $finder->findAll('Age = ?', $age);
Tip: You may also use OR as a condition in the dynamic methods.

findBySql()

Finds records using full SQL, returns corresponding array of record objects.

count()

Find the number of matchings records.

Inserting and updating records

Add a new record using TActiveRecord is very simple, just create a new Active Record object and call the save() method. E.g.

$user1 = new UserRecord(); $user1->username = "admin"; $user1->email = "admin@example.com"; $user1->save(); //insert a new record $data = array('username'=>'admin', 'email'=>'admin@example.com'); $user2 = new UserRecord($data); //create by passing some existing data $user2->save(); //insert a new record
Tip: The objects are update with the primary key of those the tables that contains definitions that automatically creates a primary key for the newly insert records. For example, if you insert a new record into a MySQL table that has columns defined with "autoincrement", the Active Record objects will be updated with the new incremented values.

To update a record in the database, just change one or more properties of the Active Record object that has been loaded from the database and then call the save() method. $user = UserRecord::finder()->findByName('admin'); $user->email="test@example.com"; //change property $user->save(); //update it.

Active Record objects have a simple life-cycle illustrated in the following diagram.

alt="Active Records Life Cycle" id="fig:cycle.png" class="figure"/>

We see that new TActiveRecord objects are created by either using one of the find*() methods or using creating a new instance by using PHP's new keyword. Objects created by a find*() method starts with clean state. New instance of TActiveRecord created other than by a find*() method starts with new state. When ever you call the save() method on the TActiveRecord object, the object enters the clean state. Objects in the clean becomes dirty whenever one of more of its internal states are changed. Calling the delete() method on the object ends the object life-cycle, no futher actions can be performed on the object.

Deleting existing records

To delete an existing record that is already loaded, just call the delete() method. You can also delete records in the database by primary keys without loading any records using the deleteByPk() method. For example, to delete one or records with tables having a scalar primary key.

$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 automatically 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), .. ));

deleteAll() and deleteBy*()

To delete by a criteria, use deleteAll($criteria) and deleteBy*() with similar synatx to findAll($criteria) and findAllBy*() as described above.

//delete all records with matching Name $finder->deleteAll('Name = ?', $name); $finder->deleteByName($name); //delete by username and password $finder->deleteBy_Username_And_Password($name,$pass);

Transactions

All Active Record objects contains the property DbConnection that can be used to obtain a transaction object. $finder = UserRecord::finder(); $finder->DbConnection->Active=true; //open if necessary $transaction = $finder->DbConnection->beginTransaction(); try { $user = $finder->findByPk('admin'); $user->email = 'test@example.com'; //alter the $user object $user->save(); $transaction->commit(); } catch(Exception $e) // an exception is raised if a query fails { $transaction->rollBack(); }

Active Record Relationships

The Prado Active Record implementation supports the foreign key mappings for database that supports foreign key contraints. For ActiveRecord relationships to function the underlying database must support foreign key constraints (e.g. MySQL with InnoDB).

In the following sections we shall consider the following table relationships between Teams, Players, Skills and Profiles.

The goal is to obtain object models that represents to some degree the entity relationships in the above figure.

There is a mismatch between relationships with objects and table relationships. First there's a difference in representation. Objects handle links by storing references that are held by the runtime memory-managed environment. Relational databases handle links by forming a key into another table. Second, objects can easily use collections to handle multiple references from a single field, while normalization forces all entity relation links to be single valued. This leads to reversals of the data structure between objects and tables. The approach taken in the Prado Active Record design is to use the table foreign key constraints to derive object relationships. This implies that the underlying database must support foreign key constraints.

Foreign Key Mapping

The entity relationship between the Teams and Players table is what is known as an 1-M relationship. That is, one Team may contain 0 or more Players. In terms of object relationships, we say that the Team object has many Player objects. (Notice the reversal of the reversal of the direction of relationships between tables and objects.)

Has Many Relationship

We model the Team object as the following Active Record classes.

class TeamRecord extends TActiveRecord { const TABLE='Teams'; public $name; public $location; public $players=array(); //define the $player member having has many relationship with PlayerRecord protected static $RELATIONS=array ( 'players' => array(self::HAS_MANY, 'PlayerRecord'), ); public static function finder($className=__CLASS__) { return parent::finder($className); } }

The static $RELATIONS property of TeamRecord defines that the property $players has many PlayerRecords. Multiple relationships is permitted by defining each relationship with an entry in the $RELATIONS array where array key for the entry corresponds to the property name. In array(self::HAS_MANY, 'PlayerRecord'), the first element defines the relationship type, the valid types are self::HAS_MANY, self::HAS_ONE and self::BELONGS_TO. The second element is a string 'PlayerRecord' that corresponds to the class name of the PlayerRecord class.

The foreign key constraint of the Players table is used to determine the corresponding Teams table's corresponding key names. This is done automatically handled in Active Record by inspecting the Players and Teams table definitions.

Info: Active Record supports multiple table foreign key relationships with the restiction that each relationship correponds to a unique table. For example, the Players table may only have one set of foreign key relationship with table Teams, it may have other relationships that corresponds to other tables (including the Players table itself).

The has many relationship is not fetched automatically when you use any of the Active Record finder methods. You will need to explicitly fetch the related objects as follows. In the code below, both lines are equivalent and the method names are case insensitive.

$team = TeamRecord::finder()->withPlayers()->findAll(); $team = TeamRecord::finder()->with_players()->findAll(); //equivalent

The method with_xxx() (where xxx is the relationship property name, in this case, players) fetchs the corresponding PlayerRecords using a second query (not by using a join). The with_xxx() accepts the same arguments as other finder methods of TActiveRecord, e.g. with_players('age < ?', 35).

Note: It is essential to understand that the related objects are fetched using additional queries. The first query fetches the source object, .e.g the TeamRecord in the above example code. A second query is used to fetche the corresponding related PlayerRecord objects. The usage of the two query is similar to a single query using Left-Outer join with the exception that null results on the right table are not returned. The consequence of using two or more queries is that the aggregates and other join conditions are not feasible using Active Records. For queries outside the scope of Active Record the SqlMap Data Mapper may be considered.

Belongs To Relationship

class PlayerRecord extends TActiveRecord { const TABLE='Players'; public $player_id; public $age; public $team_name; public $team; public $skills=array(); public $profile; protected static $RELATIONS=array ( 'team' => array(self::BELONGS_TO, 'TeamRecord'), 'skills' => array(self::HAS_MANY, 'SkillRecord', 'Player_Skills'), 'profile' => array(self::HAS_ONE, 'ProfileRecord'), ); public static function finder($className=__CLASS__) { return parent::finder($className); } }

Has One Relationship

class ProfileRecord extends TActiveRecord { const TABLE='Profiles'; public $player_id; public $salary; public $player; protected static $RELATIONS=array ( 'player' => array(self::BELONGS_TO, 'PlayerRecord'), ); public static function finder($className=__CLASS__) { return parent::finder($className); } }

Association Table Mapping

class SkillRecord extends TActiveRecord { const TABLE='Skills'; public $skill_id; public $name; public $players=array(); protected static $RELATIONS=array ( 'players' => array(self::HAS_MANY, 'PlayerRecord', 'Player_Skills'), ); public static function finder($className=__CLASS__) { return parent::finder($className); } }

References

$Id$