Class CoughObject

Description

CoughObject is the foundation for which all other "Model" / "ORM" classes extend. There will usually be one class extending CoughObject for each table in the database that an ORM is needed for.

It might be wise to add your own AppModel / AppCoughObject class that extends CoughObject and have all your classes extend that one; this way you can add custom functionality to Cough without modifying the Cough source.

  • abstract:

Located in /cough/CoughObject.class.php (line 14)


	
			
Variable Summary
Method Summary
static As_SelectQuery buildSelectQuery ( $className)
static mixed constructByKey (mixed $idOrHash, [ $className = ''])
static mixed constructBySql (string $sql, [ $className = ''])
static array getFieldAliases (string $className, string $objectName, [string $tableName = ''])
static array getKeysWithPrefix ( &$arr, string $prefix, array $arr)
static void splitArrayWithPrefix ( &$arr, string $prefix, array $arr)
static void titleCase ( $underscoredString)
static void underscore ( $camelCasedString)
static void unsetKeysWithPrefix ( &$arr, string $prefix, array $arr)
void __construct ([$fieldsOrID $fieldsOrID = array()], [ $relatedEntities = array()])
void defineFields ()
void defineObjects ()
void deflate ()
boolean delete ()
void doValidateData ( &$data)
mixed getDerivedField (string $fieldName)
mixed getField ( $fieldName)
array getFields ()
associative getInsertFields ()
mixed getKeyId ()
associative getModifiedFields ()
array getPk ()
associative getUpdateFields ()
boolean hasKeyId ()
boolean hasModifiedFields ()
void inflate ([ $fieldsOrId = array()], [ $relatedEntities = array()])
void inflateObject ( $objectName,  $objectData, [ &$additionalData = array()])
boolean insert ()
void invalidateField (string $fieldName, [string $msg = ''])
boolean isDataValid ()
boolean isDeleted ()
boolean isEqualTo ( $coughObject)
boolean isFieldModified ( $fieldName)
boolean isFieldValid (string $fieldName)
boolean isInflated ()
boolean isNew ()
void resetModified ()
boolean save ()
void setDerivedField (string $fieldName, mixed $fieldValue)
void setField (string $fieldName, mixed $value)
void setFields (array $fields)
void setFieldsIfDifferent (array $fields)
void setFieldsThroughSetters (array $fields)
void setKeyId (mixed $id, [boolean $notifyChildren = true])
void setModifiedField (string $fieldName)
boolean shouldInsert ()
boolean update ()
boolean validateData ([ &$data = null], array $data)
void __clone ()
Variables
array $collections = array() (line 59)

An array of all the loaded collections in form [collectionName] => [CoughCollection]

array $derivedFieldDefinitions = array() (line 123)

An array of derived field definitions

Format of "derived_field_name" => attributes

array $derivedFields = array() (line 43)

An array of derived fields (read-only, as in not saved back to the database).

Format of "derived_field_name" => value

array $fieldDefinitions = array() (line 113)

An array of all the columns in the database, including the primary key column and name columns.

Format of "field_name" => attributes

array $fields = array() (line 24)

An array of all the currently initialized or set fields.

Format of "field_name" => value

boolean $isDeleted = false (line 69)

Stores whether or not the object has been deleted from the database.

Save will do nothing if an object has been deleted...

boolean $isNew = true (line 84)

Stores whether or not the object is new (i.e. not in database yet).

Save will perform an INSERT if $isNew is true, otherwise it will perform an UPDATE as long as hasKeyId() also returns true.

Note that isNew() = !isInflated(). That is, any time an object is inflated, it is considered to be synced with the database, and therefore not new.

array $modifiedFields = array() (line 32)

An array of fields that have been modified.

array $objectDefinitions = array() (line 138)

An array of all the objects and their attributes.

The information is used by CoughObject to instantiate and load the objects.

Format of [objectName] => [array of attributes]

TODO: Document that array of attributes. For now just look at the one of the generated class's defineObjects().

  • access: protected
array $objects = array() (line 51)

An array of all the loaded objects in form [objectName] => [CoughObject]

boolean $validatedData = false (line 102)

Keep track of whether or not data has been validated.

array $validationErrors = array() (line 94)

Stores validation errors set by `validateData` function.

Format of "field_name" => "Error Text"

Methods
static method buildSelectQuery (line 1178)

Builds a basic SELECT table.* FROM db.table query object (making it easy to inject joins, where criteria, order by, group by, etc.)

  • author: Anthony Bush
  • todo: PHP 5.3+: use "static" keyword instead of call_user_func and remove the parameter requirement (making sure that if called with it, no warnings/notices are generated; i.e. keep backward compatibility)
  • since: 2008-08-26
  • access: public
static As_SelectQuery buildSelectQuery ( $className)
  • $className
static method constructByKey (line 217)

Constructs a new object from a single id (for single key PKs) or a hash of [field_name] => [field_value].

The key is used to pull data from the database, and, if no data is found, null is returned. You can use this function with any unique keys or the primary key as long as a hash is used. If the primary key is a single field, you may pass its value in directly without using a hash.

  • return: - CoughObject or null if no record found.
  • todo: PHP 5.3: switch from call_user_func to static::methodName() and remove the $className parameter
  • access: public
static mixed constructByKey (mixed $idOrHash, [ $className = ''])
  • mixed $idOrHash: - id or hash of [field_name] => [field_value]
  • $className
static method constructBySql (line 250)

Constructs a new object from custom SQL.

  • return: - CoughObject if exactly one row found, null otherwise.
  • todo: PHP 5.3: switch from call_user_func to static::methodName() and remove the $className parameter
  • access: public
static mixed constructBySql (string $sql, [ $className = ''])
  • string $sql
  • $className
static method getFieldAliases (line 1150)

Helper method for generating SELECT criteria for other join tables.

For example, you might need the following SQL:

  1.      $sql '
  2.      SELECT
  3.          product.*
  4.          , `manufacturer`.`manufacturer_id` AS `Manufacturer_Object.manufacturer_id`
  5.          , `manufacturer`.`name` AS `Manufacturer_Object.name`
  6.          , `manufacturer`.`description` AS `Manufacturer_Object.description`
  7.          , `manufacturer`.`url` AS `Manufacturer_Object.url`
  8.      FROM
  9.          product
  10.          INNER JOIN manufacturer USING (manufacturer_id)
  11.      ';

But, rather than hand coding all the fields (which might change) on the manufacturer join, you can use getFieldAliases():

  1.      $sql '
  2.      SELECT
  3.          product.*
  4.          , ' implode("\n\t, "CoughObject::getFieldAliases('con_Manufacturer''Manufacturer_Object')) '
  5.      FROM
  6.          product
  7.          INNER JOIN manufacturer USING (manufacturer_id)
  8.      ';

  • return: of field Aliases
  • author: Anthony Bush, Richard Pistole
  • since: 2008-02-21
  • access: public
static array getFieldAliases (string $className, string $objectName, [string $tableName = ''])
  • string $className: class to get fields for, e.g. Address
  • string $objectName: object to alias fields to, e.g. BillingAddress_Object
  • string $tableName: optional table name; use if aliasing the table name (e.g. address to billing_address)
static method getKeysWithPrefix (line 1067)

Returns a sub array of the given array containing all elements that have keys starting with the specified prefix. The resulting array's keys have the prefix removed.

  • author: Anthony Bush, Richard Pistole
  • since: 2008-02-20
  • access: public
static array getKeysWithPrefix ( &$arr, string $prefix, array $arr)
  • array $arr
  • string $prefix
  • &$arr
static method splitArrayWithPrefix (line 1095)

Returns a sub array of the given array containing all elements that have keys starting with the specified prefix. The resulting array's keys have the prefix removed.

The array passed by reference has all the items that were added to the returned array removed.

  • author: Anthony Bush, Richard Pistole
  • since: 2008-02-20
  • access: public
static void splitArrayWithPrefix ( &$arr, string $prefix, array $arr)
  • array $arr
  • string $prefix
  • &$arr
static method titleCase (line 1028)
  • access: public
static void titleCase ( $underscoredString)
  • $underscoredString
static method underscore (line 1032)
  • access: public
static void underscore ( $camelCasedString)
  • $camelCasedString
static method unsetKeysWithPrefix (line 1045)

Unsets all keys on the given array that start with the specified prefix.

  • author: Anthony Bush, Richard Pistole
  • since: 2008-02-20
  • access: public
static void unsetKeysWithPrefix ( &$arr, string $prefix, array $arr)
  • array $arr
  • string $prefix
  • &$arr
Constructor __construct (line 150)

Construct an empty CoughObject or an object with pre-initialized data.

  • access: public
void __construct ([$fieldsOrID $fieldsOrID = array()], [ $relatedEntities = array()])
  • $fieldsOrID $fieldsOrID: - initializes the object with the fields or id (does not query the database)
  • $relatedEntities
clearValidationErrors (line 1023)

Clear validation status.

  • author: Anthony Bush
  • access: public
void clearValidationErrors ()
defineDerivedFields (line 187)

Override in sub-class to define derived fields the object may possess.

  • access: protected
void defineDerivedFields ()
defineFields (line 180)

Override in sub-class to define fields the object possesses, including $pkFieldNames.

  • access: protected
void defineFields ()
defineObjects (line 194)

Override in sub-class to define objects the object possesses.

  • access: protected
void defineObjects ()
deflate (line 1194)

Returns object to it's own state, except what you want to keep. By default it empties everything; overridden version only empties yours.

  • todo: Tom: Why this function? (provide good example so it can be added to documentation)
  • access: public
void deflate ()
delete (line 904)

Deletes the record from the database, if hasKeyId returns true.

Override this for special delete functionality. For example, if an object should never be deleted, but instead just retired, then override this to look like:

$this->setIsRetired(true); $this->save();

Then just make sure the load queries include is_retired = 0 in the WHERE clause so that the item is not pulled from the database (i.e. it appears deleted, but the data is still there for historical reference/backup.)

Usually, the coder will be the only one to call delete, but Cough will call it on join objects when removing objects in a many-to-many collection.

  • return: - whether or not the delete was executed.
  • author: Anthony Bush
  • access: public
boolean delete ()
doValidateData (line 961)

Do the actual data validation. Override in sub classes.

void doValidateData ( &$data)
  • &$data
finishConstruction (line 202)

Called at the end of __construct(). Override for special construction behavior that is dependent on the object's state.

  • access: protected
void finishConstruction ()
getDerivedField (line 648)

Returns the specified derived field name.

mixed getDerivedField (string $fieldName)
  • string $fieldName: - the derived field name to retrieve
getField (line 548)

Returns the current value of the requested field name.

  • access: protected
mixed getField ( $fieldName)
  • $fieldName
getFields (line 507)

Returns the object's fields as an array of [key] => [value] pairs.

Only the fields that directly correspond to columns in the database are returned. This means no:

  • derived fields
  • join fields
  • objects for one-to-one or one-to-many relationships
It's useful if you need to pass on just the data of the object but not the object itself, either for displaying in an HTML form, storing in the session for later retrieval, etc.

For example, you can store the raw data in a session and reconstruct the object with it later, so you don't waste space in the session, and you don't have to re-pull the data from the database:

// E.g. save user data when they log in. $_SESSION['User'] = $user->getFields();

// Then reconstruct the object later: $user = new User($_SESSION['User']);

  • author: Anthony Bush
  • access: public
array getFields ()
getFieldsThroughGetters (line 518)

Gets fields by going through their getter methods, so that polymorphism is not broken (you can override getFieldName(), and that is the value you'll get).

  • return: - format of [field_name] => [new_value]
  • since: 2008-12-18
  • access: public
array getFieldsThroughGetters ()
getFieldsWithoutPk (line 535)

Get all non-primary key related fields and their values.

  • author: Anthony Bush
  • since: 2007-07-06
  • access: public
array getFieldsWithoutPk ()
getInsertFields (line 840)

Returns the fields that should be used for inserting. This logic is separate from the insert method to make it easy to override the behavior.

  • return: array [field_name] => [field_value]
  • author: Anthony Bush
  • access: protected
associative getInsertFields ()
getKeyId (line 411)

Returns the current value of the object's primary key id.

If the key is multi-key, this returns a unique string identifying itself (a concatenation of the fields making up the PK).

  • return: - string for multi-key PKs, integer/string for single-key PKs
  • author: Anthony Bush
  • access: public
mixed getKeyId ()
getModifiedFields (line 689)

Get a list of all of this object's modified values.

  • return: array - all modified values in [field_name] => [old_value] form
  • access: protected
associative getModifiedFields ()
getPk (line 431)

Returns the primary key as an array of [field_name] => field_value pairs

  • author: Anthony Bush
  • since: 2007-07-06
  • access: public
array getPk ()
getUpdateFields (line 875)

Returns the fields that should be used for updating. This logic is separate from the update method to make it easy to override the behavior.

  • return: array [field_name] => [field_value]
  • author: Anthony Bush
  • access: protected
associative getUpdateFields ()
getValidationErrors (line 1013)

Returns the validation errors set by `validateData()`.

  • author: Anthony Bush
  • access: public
array getValidationErrors ()
hasKeyId (line 447)

Returns true if all the key fields that make up the primary key are set to non-null values.

  • author: Anthony Bush
  • todo: If NULL is a valid value for a PK, this function needs an update.
  • access: public
boolean hasKeyId ()
hasModifiedFields (line 699)

Whether or not there is at least one modified field.

  • author: Anthony Bush
  • access: public
boolean hasModifiedFields ()
inflate (line 1208)

Inflate/Invigorate the object with data.

  • access: public
void inflate ([ $fieldsOrId = array()], [ $relatedEntities = array()])
  • $fieldsOrId
  • $relatedEntities
inflateObject (line 1258)

This helper method for inflate() handles inflation of related objects.

  • access: protected
void inflateObject ( $objectName,  $objectData, [ &$additionalData = array()])
  • $objectName
  • $objectData
  • &$additionalData
initializeDefinitions (line 168)

Sets the cough object's basic identity:

  • access: protected
void initializeDefinitions ()
insert (line 812)

Inserts a new row to the database and sets the object's key id with the returned database insert id.

If the object has a multi-key PK, then the key is not set after insert.

By default, only values that have been modified are used in the INSERT statement, leaving it up to the database to set default values for the other fields. To change this, override the getInsertFields() method.

  • author: Anthony Bush
  • access: protected
boolean insert ()
invalidateField (line 972)

Invalidates a field with an optional message.

  • author: Anthony Bush
  • access: public
void invalidateField (string $fieldName, [string $msg = ''])
  • string $fieldName: - field to invalidate
  • string $msg: - optional message to store of why data is invalid.
isDataValid (line 999)

Returns true if the data is valid (i.e. no validation errors set), otherwise it returns false.

  • author: Anthony Bush
  • access: public
boolean isDataValid ()
isDeleted (line 923)

Specifies whether or not the object has been deleted from the database.

  • author: Anthony Bush
  • access: public
boolean isDeleted ()
isEqualTo (line 304)

This will compare two CoughObjects and return true if they are of the same type and have the same field values (excluding the primary key).

Feel free to override this in sub classes for customized comparison.

  • author: Anthony Bush
  • access: public
boolean isEqualTo ( $coughObject)
  • $coughObject
isFieldModified (line 714)

Whether or not the specified field has been modified.

  • author: Anthony Bush
  • since: 2008-09-03
  • access: public
boolean isFieldModified ( $fieldName)
  • $fieldName
isFieldValid (line 984)

Returns true if the field is valid (i.e. no validation errors set), otherwise it returns false.

  • author: Anthony Bush
  • access: public
boolean isFieldValid (string $fieldName)
  • string $fieldName: - the field name to load.
isInflated (line 398)

Returns whether or not the object is inflated (i.e. pulled from persistent storage)

This method returns the opposite of isNew()

The reason this method isn't called `isLoaded()` is because it's possible for an object to become inflated from data that was not loaded from a database / persistent storage. It's meant to answer the question, "Can I call the getters on this object and expect to get meaningful values?"

boolean isInflated ()
isNew (line 379)

Returns whether or not the object is new (i.e. not in persistent storage)

This method returns the opposite of isInflated()

boolean isNew ()
notifyChildrenOfKeyChange (line 366)

This method's job is to notify related collections (if any) of the key change.

For example, if the schema is "order has many order lines" then on the Order object the `notifyChildrenOfKeyChange` function might change the order_id on all the order_line entities. The code might look like:

foreach ($this->getOrderLine_Collection() as $orderLine) { $orderLine->setOrderId($key['order_id']); }

  • author: Anthony Bush
  • access: public
void notifyChildrenOfKeyChange ( $pk)
  • array $pk
resetModified (line 670)

Clear the list of modified fields and other modified flags.

  • access: protected
void resetModified ()
save (line 730)

Creates a new entry if needed, otherwise it updates an existing one.

During an update, it only updates the modified fields. During an insert, it only inserts modified fields (leaving defaults up to the database server).

  • return: - the result of the create/update.
  • author: Anthony Bush
  • access: public
boolean save ()
saveLoadedCollections (line 792)

Saves all the loaded collections (if it wasn't loaded there would be nothing to save)

  • author: Anthony Bush
  • access: public
void saveLoadedCollections ()
saveLoadedObjects (line 779)

Saves all the loaded objects (if it wasn't loaded there would be nothing to save)

  • author: Anthony Bush
  • access: public
void saveLoadedObjects ()
setDerivedField (line 636)

Sets a read-only field; It's usually a derived field from a complex SQL query such as when overriding the getLoadSql() function.

  • author: Anthony Bush
  • see: getLoadSql()
  • access: protected
void setDerivedField (string $fieldName, mixed $fieldValue)
  • string $fieldName: - the derived field name to set
  • mixed $fieldValue: - the value to store
setField (line 563)

Sets the current value of $fieldName to $value.

  • access: protected
void setField (string $fieldName, mixed $value)
  • string $fieldName
  • mixed $value
setFields (line 576)

Sets the current value of the all the object's defined fields equal to the values passed in the $fields associative array.

Note: if a field passed in the fields associative array isn't in the class's defined fields, it will NOT BE SET.

  • access: public
void setFields (array $fields)
  • array $fields: - format of [field_name] => [new_value]
setFieldsIfDifferent (line 614)

Sets fields in the given hash, but only if they new values are different from the existing values

  • author: Anthony Bush
  • since: 2007-08-02
  • access: public
void setFieldsIfDifferent (array $fields)
  • array $fields: - format of [field_name] => [new_value]
setFieldsThroughSetters (line 595)

Sets fields by going through their setter methods, so that polymorphism is not broken (you can override setFieldName($val), and that is the method that will be called).

  • since: 2008-12-17
  • access: public
void setFieldsThroughSetters (array $fields)
  • array $fields: - format of [field_name] => [new_value]
setKeyId (line 337)

Sets the object's primary key id to the passed value.

If key is multi-key:

* Call this with an array of [field_name] => [field_value] pairs to set all values uniquely.

* Call this with a non-array value to set all keys to the same value.

  • author: Anthony Bush
  • access: public
void setKeyId (mixed $id, [boolean $notifyChildren = true])
  • mixed $id
  • boolean $notifyChildren: whether or not to notify children (collections) of the key change. Think of it as a cascade update of the FKs.
setModifiedField (line 680)

Add a field to the list of modified fields

  • access: protected
void setModifiedField (string $fieldName)
  • string $fieldName
shouldInsert (line 764)

Indicates whether or not a save should insert a new record or update an existing one.

  • return: - true = insert new, false = update existing one
  • author: Anthony Bush
  • access: protected
boolean shouldInsert ()
update (line 853)

Updates the database with modified values, if any.

  • return: - true
  • access: protected
boolean update ()
validateData (line 943)

Validates data stored in the model. It is called automatically by `save`, which will return false if this function sets any errors.

If you pass it nothing, it will validate with the current data stored in the object.

boolean validateData ([ &$data = null], array $data)
  • array $data: - the data to validate in [field_name] => [value] form.
  • &$data
__clone (line 277)

Clone only the non-primary key fields.

Usage: $newProduct = clone $product;

  • author: Lewis Zhang
  • author: Anthony Bush
  • access: public
void __clone ()

Documentation generated on Fri, 19 Dec 2008 11:03:50 -0600 by phpDocumentor 1.4.0