PHP 클래스 Prado\Data\ActiveRecord\TActiveRecord

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 = '[email protected]'; $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; public $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. Since v3.1.2, TActiveRecord enhanced its support to access of foreign objects. By declaring a public static variable RELATIONS like the following, one can access the corresponding foreign objects easily: class UserRecord extends TActiveRecord { const TABLE='users'; public static $RELATIONS=array ( 'department'=>array(self::BELONGS_TO, 'DepartmentRecord', 'department_id'), 'contacts'=>array(self::HAS_MANY, 'ContactRecord', 'user_id'), ); } In the above, the users table is related with departments table (represented by DepartmentRecord) and contacts table (represented by ContactRecord). Now, given a UserRecord instance $user, one can access its department and contacts simply by: $user->department and $user->contacts. No explicit data fetching is needed. Internally, the foreign objects are fetched in a lazy way, which avoids unnecessary overhead if the foreign objects are not accessed at all. Since v3.1.2, new events OnInsert, OnUpdate and OnDelete are available. The event OnInsert, OnUpdate and OnDelete methods are executed before inserting, updating, and deleting the current record, respectively. You may override these methods; a TActiveRecordChangeEventParameter parameter is passed to these methods. The property {@link TActiveRecordChangeEventParameter::setIsValid IsValid} of the parameter can be set to false to prevent the change action to be executed. This can be used, for example, to validate the record before the action is executed. For example, in the following the password property is hashed before a new record is inserted. class UserRecord extends TActiveRecord { function OnInsert($param) { parent method should be called to raise the event parent::OnInsert($param); $this->nounce = md5(time()); $this->password = md5($this->password.$this->nounce); } } Since v3.1.3 you can also define a method that returns the table name. class UserRecord extends TActiveRecord { public function table() { return 'users'; } }
부터: 3.1
상속: extends Prado\TComponent
파일 보기 프로젝트 열기: pradosoft/prado 1 사용 예제들

공개 프로퍼티들

프로퍼티 타입 설명
$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.
$RELATIONS The keys are public variable/property names defined in the AR class. Each value is an array, e.g. array(self::HAS_MANY, 'PlayerRecord').

보호된 프로퍼티들

프로퍼티 타입 설명
$_connection database connection object.
$_invalidFinderResult TActiveRecordInvalidFinderResult Defaults to 'null'
$_recordState record state: 0 = new, 1 = loaded, 2 = deleted.

공개 메소드들

메소드 설명
__call ( $method, $args ) : mixed Dynamic find method using parts of method name as search criteria.
__construct ( $data = [], $connection = null ) Create a new instance of an active record with given $data. The record can be saved to the database specified by the $connection object.
__get ( $name ) : mixed Magic method for reading properties.
__set ( $name, $value ) Magic method for writing properties.
__sleep ( ) Prevent __call() method creating __sleep() when serializing.
__wakeup ( ) Prevent __call() method creating __wakeup() when unserializing.
copyFrom ( $data ) Copies data from an array or another object.
count ( $criteria = null, $parameters = [] ) : integer Find the number of records.
createRecord ( $type, $data ) : TActiveRecord Create an AR instance specified by the AR class name and initial data.
delete ( ) : boolean Deletes the current record from the database. Once deleted, this object can not be saved again in the same instance.
deleteAll ( $criteria = null, $parameters = [] ) : integer Delete multiple records using a criteria.
deleteAllByPks ( $keys ) Alias for deleteByPk()
deleteByPk ( $keys ) : integer Delete records by primary key. Usage:
equals ( TActiveRecord $record, $strict = false ) : boolean 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 (===).
find ( $criteria, $parameters = [] ) : TActiveRecord Find one single record that matches the criteria.
findAll ( $criteria = null, $parameters = [] ) : array Same as find() but returns an array of objects.
findAllByIndex ( $criteria, $fields, $values ) : array 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.
findAllByPks ( $keys ) : array Find multiple records matching a list of primary or composite keys.
findAllBySql ( $sql, array $parameters = [] ) : array Find records using full SQL, returns corresponding record object.
findByPk ( $keys ) : TActiveRecord. Find one record using only the primary key or composite primary keys. Usage:
findBySql ( $sql, array $parameters = [] ) : TActiveRecord, Find records using full SQL, returns corresponding record object.
finder ( $className = __CLASS__ ) : TActiveRecord Returns the instance of a active record finder for a particular class.
getActiveDbConnection ( )
getColumnValue ( $columnName ) : mixed Retrieves the column value according to column name.
getDbConnection ( ) : TDbConnection Gets the current Db connection, the connection object is obtained from the TActiveRecordManager if connection is currently null.
getInvalidFinderResult ( ) : TActiveRecordInvalidFinderResult
getRecordGateway ( ) : TActiveRecordGateway
getRecordManager ( ) : TActiveRecordManager Gets the record manager for this object, the default is to call TActiveRecordManager::getInstance().
getRecordRelation ( $property ) : array
getRecordRelations ( ) : array
getRecordTableInfo ( ) : TDbTableInfo
hasRecordRelation ( $property ) : boolean
onCreateCommand ( $param ) Raised when a command is prepared and parameter binding is completed.
onDelete ( $param ) Raised before the record attempt to delete its data from the database.
onExecuteCommand ( $param ) Raised when a command is executed and the result from the database was returned.
onInsert ( $param ) Raised before the record attempt to insert its data into the database.
onUpdate ( $param ) Raised before the record attempt to update its data in the database.
save ( ) : boolean Saves the current record to the database, insert or update is automatically determined.
setColumnValue ( $columnName, $value ) Sets the column value according to column name.
setDbConnection ( $connection )
setInvalidFinderResult ( $value ) Define the way an active record finder react if an invalid magic-finder invoked
toArray ( ) : array Return record data as array
toJSON ( ) : JSON Return record data as JSON

보호된 메소드들

메소드 설명
createRelationContext ( $name ) : TActiveRecordRelationContext Gets a static copy of the relationship context for given property (a key in $RELATIONS), returns null if invalid relationship. Keeps a null reference to all invalid relations called.
fetchResultsFor ( $property ) : boolean Tries to load the relationship results for the given property. The $property value should correspond to an entry key in the $RELATION array.
getRecordCriteria ( $criteria, $parameters, $args = [] ) : TSqlCriteria 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.
getRelationHandler ( $name, $args = [] ) : TActiveRecordRelation, Returns the active record relationship handler for $RELATION with key value equal to the $property value.
populateObject ( $data ) : TActiveRecord Populates a new record with the query result.
populateObjects ( $reader ) : array

비공개 메소드들

메소드 설명
setupColumnMapping ( )
setupRelations ( )

메소드 상세

__call() 공개 메소드

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);
public __call ( $method, $args ) : mixed
리턴 mixed single record if method name starts with "findBy", 0 or more records if method name starts with "findAllBy"

__construct() 공개 메소드

Create a new instance of an active record with given $data. The record can be saved to the database specified by the $connection object.
public __construct ( $data = [], $connection = null )

__get() 공개 메소드

This method is overriden to provide read access to the foreign objects via the key names declared in the RELATIONS array.
부터: 3.1.2
public __get ( $name ) : mixed
리턴 mixed property value.

__set() 공개 메소드

This method is overriden to provide write access to the foreign objects via the key names declared in the RELATIONS array.
부터: 3.1.2
public __set ( $name, $value )

__sleep() 공개 메소드

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

__wakeup() 공개 메소드

Prevent __call() method creating __wakeup() when unserializing.
public __wakeup ( )

copyFrom() 공개 메소드

Copies data from an array or another object.
public copyFrom ( $data )

count() 공개 메소드

Find the number of records.
public count ( $criteria = null, $parameters = [] ) : integer
리턴 integer number of records.

createRecord() 공개 정적인 메소드

If the initial data is empty, the AR object will not be created and null will be returned. (You should use the "new" operator to create the AR instance in that case.)
부터: 3.1.2
public static createRecord ( $type, $data ) : TActiveRecord
리턴 TActiveRecord the initialized AR object. Null if the initial data is empty.

createRelationContext() 보호된 메소드

Gets a static copy of the relationship context for given property (a key in $RELATIONS), returns null if invalid relationship. Keeps a null reference to all invalid relations called.
부터: 3.1.2
protected createRelationContext ( $name ) : TActiveRecordRelationContext
리턴 Prado\Data\ActiveRecord\Relations\TActiveRecordRelationContext object containing information on the active record relationships for given property, null if invalid relationship

delete() 공개 메소드

Deletes the current record from the database. Once deleted, this object can not be saved again in the same instance.
public delete ( ) : boolean
리턴 boolean true if the record was deleted successfully, false otherwise.

deleteAll() 공개 메소드

Delete multiple records using a criteria.
public deleteAll ( $criteria = null, $parameters = [] ) : integer
리턴 integer number of records deleted.

deleteAllByPks() 공개 메소드

Alias for deleteByPk()
public deleteAllByPks ( $keys )

deleteByPk() 공개 메소드

$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), .. ));
public deleteByPk ( $keys ) : integer
리턴 integer number of records deleted.

equals() 공개 메소드

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 (===).
public equals ( TActiveRecord $record, $strict = false ) : boolean
$record TActiveRecord
리턴 boolean true if $record equals, false otherwise.

fetchResultsFor() 보호된 메소드

This method can be used to lazy load relationships. class TeamRecord extends TActiveRecord { ... private $_players; public static $RELATION=array ( 'players' => array(self::HAS_MANY, 'PlayerRecord'), ); public function setPlayers($array) { $this->_players=$array; } public function getPlayers() { if($this->_players===null) $this->fetchResultsFor('players'); return $this->_players; } } Usage example: $team = TeamRecord::finder()->findByPk(1); var_dump($team->players); //uses lazy load to fetch 'players' relation
부터: 3.1.2
protected fetchResultsFor ( $property ) : boolean
리턴 boolean true if relationship exists, false otherwise.

find() 공개 메소드

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.
public find ( $criteria, $parameters = [] ) : TActiveRecord
리턴 TActiveRecord matching record object. Null if no result is found.

findAll() 공개 메소드

Same as find() but returns an array of objects.
public findAll ( $criteria = null, $parameters = [] ) : array
리턴 array matching record objects. Empty array if no result is found.

findAllByIndex() 공개 메소드

This method is to be used by the relationship handler.
public findAllByIndex ( $criteria, $fields, $values ) : array
리턴 array matching active records. Empty array is returned if no result is found.

findAllByPks() 공개 메소드

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), ...));
public findAllByPks ( $keys ) : array
리턴 array matching ActiveRecords. Empty array is returned if no result is found.

findAllBySql() 공개 메소드

The names of the column retrieved must be defined in your Active Record class.
public findAllBySql ( $sql, array $parameters = [] ) : array
$parameters array
리턴 array matching active records. Empty array is returned if no result is found.

findByPk() 공개 메소드

$finder->findByPk($primaryKey); $finder->findByPk($key1, $key2, ...); $finder->findByPk(array($key1,$key2,...));
public findByPk ( $keys ) : TActiveRecord.
리턴 TActiveRecord.

findBySql() 공개 메소드

The names of the column retrieved must be defined in your Active Record class.
public findBySql ( $sql, array $parameters = [] ) : TActiveRecord,
$parameters array
리턴 TActiveRecord,

finder() 공개 정적인 메소드

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.
public static finder ( $className = __CLASS__ ) : TActiveRecord
리턴 TActiveRecord active record finder instance.

getActiveDbConnection() 공개 정적인 메소드

public static getActiveDbConnection ( )

getColumnValue() 공개 메소드

This method is used internally.
부터: 3.1.1
public getColumnValue ( $columnName ) : mixed
리턴 mixed the corresponding column value

getDbConnection() 공개 메소드

Gets the current Db connection, the connection object is obtained from the TActiveRecordManager if connection is currently null.
public getDbConnection ( ) : TDbConnection
리턴 TDbConnection current db connection for this object.

getInvalidFinderResult() 공개 메소드

또한 보기: TActiveRecordManager::getInvalidFinderResult
부터: 3.1.5
public getInvalidFinderResult ( ) : TActiveRecordInvalidFinderResult
리턴 TActiveRecordInvalidFinderResult Defaults to '{@link TActiveRecordInvalidFinderResult::Null Null}'.

getRecordCriteria() 보호된 메소드

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.
protected getRecordCriteria ( $criteria, $parameters, $args = [] ) : TSqlCriteria
리턴 Prado\Data\DataGateway\TSqlCriteria criteria object.

getRecordGateway() 공개 메소드

public getRecordGateway ( ) : TActiveRecordGateway
리턴 TActiveRecordGateway record table gateway.

getRecordManager() 공개 정적인 메소드

Gets the record manager for this object, the default is to call TActiveRecordManager::getInstance().
public static getRecordManager ( ) : TActiveRecordManager
리턴 TActiveRecordManager default active record manager.

getRecordRelation() 공개 메소드

부터: 3.1.2
public getRecordRelation ( $property ) : array
리턴 array relation definition for the specified property

getRecordRelations() 공개 메소드

부터: 3.1.2
public getRecordRelations ( ) : array
리턴 array all relation definitions declared in the AR class

getRecordTableInfo() 공개 메소드

public getRecordTableInfo ( ) : TDbTableInfo
리턴 TDbTableInfo the meta information of the table associated with this AR class.

getRelationHandler() 보호된 메소드

Returns the active record relationship handler for $RELATION with key value equal to the $property value.
protected getRelationHandler ( $name, $args = [] ) : TActiveRecordRelation,
리턴 TActiveRecordRelation,

hasRecordRelation() 공개 메소드

부터: 3.1.2
public hasRecordRelation ( $property ) : boolean
리턴 boolean whether a relation is declared for the specified AR property

onCreateCommand() 공개 메소드

The parameter object is TDataGatewayEventParameter of which the {@link TDataGatewayEventParameter::getCommand Command} 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.
public onCreateCommand ( $param )

onDelete() 공개 메소드

To prevent the delete operation, set the TActiveRecordChangeEventParameter::IsValid parameter to false.
public onDelete ( $param )

onExecuteCommand() 공개 메소드

The parameter object is TDataGatewayResultEventParameter of which the {@link TDataGatewayEventParameter::getResult Result} property contains the data return from the database. The data returned can be changed by setting the {@link TDataGatewayEventParameter::setResult Result} 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.
public onExecuteCommand ( $param )

onInsert() 공개 메소드

To prevent the insert operation, set the TActiveRecordChangeEventParameter::IsValid parameter to false.
public onInsert ( $param )

onUpdate() 공개 메소드

To prevent the update operation, set the TActiveRecordChangeEventParameter::IsValid parameter to false.
public onUpdate ( $param )

populateObject() 보호된 메소드

This is a wrapper of {@link createRecord}.
protected populateObject ( $data ) : TActiveRecord
리턴 TActiveRecord object record, null if data is empty.

populateObjects() 보호된 메소드

부터: 3.1.2
protected populateObjects ( $reader ) : array
리턴 array the AR objects populated by the query result

save() 공개 메소드

Saves the current record to the database, insert or update is automatically determined.
public save ( ) : boolean
리턴 boolean true if record was saved successfully, false otherwise.

setColumnValue() 공개 메소드

This method is used internally.
부터: 3.1.1
public setColumnValue ( $columnName, $value )

setDbConnection() 공개 메소드

public setDbConnection ( $connection )

setInvalidFinderResult() 공개 메소드

Define the way an active record finder react if an invalid magic-finder invoked
또한 보기: TActiveRecordManager::setInvalidFinderResult
부터: 3.1.5
public setInvalidFinderResult ( $value )

toArray() 공개 메소드

Return record data as array
부터: 3.2.4
public toArray ( ) : array
리턴 array of column name and column values

toJSON() 공개 메소드

Return record data as JSON
부터: 3.2.4
public toJSON ( ) : JSON
리턴 JSON

프로퍼티 상세

$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.
부터: 3.1.1
public static $COLUMN_MAPPING

$RELATIONS 공개적으로 정적으로 프로퍼티

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

$_connection 보호되어 있는 프로퍼티

database connection object.
protected $_connection

$_invalidFinderResult 보호되어 있는 프로퍼티

Defaults to 'null'
부터: 3.1.5
protected TActiveRecordInvalidFinderResult,Prado\Data\ActiveRecord $_invalidFinderResult
리턴 TActiveRecordInvalidFinderResult

$_recordState 보호되어 있는 프로퍼티

record state: 0 = new, 1 = loaded, 2 = deleted.
부터: 3.1.2
protected $_recordState