Fakoli Framework
DataItem Class Reference

DataItem is the generic base class for database mapped classes. More...

+ Inheritance diagram for DataItem:
+ Collaboration diagram for DataItem:

Public Member Functions

 DataItem ()
 Constructor. More...
 
 __sleep ()
 
 fireEvent ($event)
 Fires the specified event to all registered handlers. More...
 
 joinTransaction ($tx)
 Join the DataItem to the specified DataTransaction. More...
 
 getTransaction ()
 Retrieves the current DataTransaction. More...
 
 cast ($class)
 Cast this object to another class. More...
 
 disablePrimaryKey ()
 
 enablePrimaryKey ()
 
 getHiddenFields ()
 
 populate ($line, $alias=false)
 Populates the object using the supplied associative array (field -> value). More...
 
 getFields ()
 Retrieve the field type list for this object. More...
 
 overrideFieldType ($field, $type)
 Override the type for the specified field. More...
 
 getFieldList ($alias="")
 Returned a comma-separated list of the fields for this object (applying the assigned filter if there is one). More...
 
 getFieldArray ()
 Return an array of field names for this object filtered by any active filter. More...
 
 hasField ($field)
 Returns true if this DataItem contains a field with the specified name and that field is not excluded by a filter. More...
 
 hasRelation ($relation)
 Returns true if this DataItem contains a relation with the specified name. More...
 
 getPrimaryKey ()
 Retrieves the primary key field name. More...
 
 getPrimaryKeyList ()
 Retrieves a list of all the primary keys used for an object as an array. More...
 
 get ($field)
 Retrieve the value for the specified field. More...
 
 set ($field, $value)
 Set the value of the specified field. More...
 
 getType ($field)
 Retrieves the data type of the specified field. More...
 
 getFilter ()
 Returns the filter set on this object. More...
 
 setFilter ($filter)
 Sets the filter on this object. More...
 
 getFieldAliases ()
 Retrieve the list of field aliases. More...
 
 getFieldAnnotations ()
 Retrieve the list of field annotations. More...
 
 load ($id)
 Load the object with the specified primary key. More...
 
 loadComposite ()
 Creates an outer CompositeDataItem from its base component. More...
 
 save ()
 Store the object in the database. More...
 
 select ()
 Select the object from the database, based on the value of the primary key field. More...
 
 exists ($constraint="")
 Check whether the object exists in the database. More...
 
 update ()
 Update the row in the database that corresponds to this object. More...
 
 updateExplicit ($updates, $params=null)
 Executes an explicit update command against the database. More...
 
 insert ()
 Insert a new row in the database to store this object. More...
 
 delete ($constraint="")
 Delete the row in the database that corresponds to this object. More...
 
 deleteAll ()
 Delete all the rows in the database that correspond to this class. More...
 
 tableExists ()
 Check if the table for this class exists in the database. More...
 
 distinctValues ($field, $sorted=false, $constraint="")
 Retrieves the distinct values in the database for the specified field across the specified set of records. More...
 
 fromGET ()
 Automatically populate the object based on parameters in the $_GET collection. More...
 
 fromPOST ()
 Automatically populate the object based on parameters in the $_POST collection. More...
 
 fromREQUEST ()
 Automatically populate the object based on parameters in either the $_GET or $_POST collection, depending on the method used to access the page. More...
 
 fromDataSet ($params)
 Automatically populate the object based on a custom set of parameters (such as a filtered $_POST collection) More...
 
 compare ($to)
 Compare this object to another object. More...
 
 copy ($from)
 Copies values from another object, field by field. More...
 
 cacheLookup ($id)
 
 getRelated ($class, $field="")
 Returns a single item related by the specified foreign key. More...
 
 getRelatedList ($class, $field="", $orderBy="")
 Returns a list of items that are related to this item. More...
 
 crossReference ($class, $xref, $orderBy="", $pkField="", $xrefField="")
 Returns a list of items related to this item via a cross-reference table. More...
 
 queryValue ($func)
 Query the database to calculate an aggregate value. More...
 
 toXML ($indent=0, $path=null)
 Generates an XML representation of the object. More...
 
 fromXML ($node)
 
 toJSON ()
 
 format ($template="", $separator=", ")
 Substitute values for field names in a string, with the fields formatted using their type's default format or according to the formatting template sting passed in. More...
 
 formatField ($template)
 
 formatThroughRelation ($template, $separator=", ")
 
 prettifyFieldName ($field)
 
 relateTo ($target, $field="")
 Link this object to the specified target by setting corresponding field to the value of the target's primary key. More...
 
- Public Member Functions inherited from AbstractDataItem
 decorate ($name, $value)
 Adds a decoration to the DataItem. More...
 
 getDecoration ($name)
 Retrieve the value of a decoration on the current DataItem. More...
 
 cast ($class)
 Cast this object to another class. More...
 
 setOption ($opt)
 Set a behavior option flag. More...
 
 clearOptions ($opt)
 Clear the specified behavior option flag. More...
 
 getConnection ()
 Retrieves a connection to the database. More...
 
 joinTransaction ($tx)
 Join the DataItem to the specified DataTransaction. More...
 
 getTransaction ()
 Retrieves the current DataTransaction. More...
 
 getIdentityConstraint ()
 Subclasses can override this function to provide additional identity constraints to be used when querying or updating. More...
 
 populate ($line)
 Populates the object using the supplied associative array (field -> value). More...
 
 getFields ()
 Retrieve the field type list for this object. More...
 
 getFieldList ($alias="")
 Returns a comma-separated list of the fields for this object (applying the assigned filter if there is one). More...
 
 getFieldArray ()
 Return an array of field names for this object filtered by any active filter. More...
 
 hasField ($field)
 Returns true if this DataItem contains a field with the specified name and that field is not excluded by a filter. More...
 
 hasRelation ($relation)
 Returns true if this DataItem contains a relation with the specified name. More...
 
 getPrimaryKey ()
 Retrieves the primary key field name. More...
 
 getPrimaryKeyList ()
 Retrieves a list of all the primary keys used for an object as an array. More...
 
 get ($field)
 Retrieve the value for the specified field. More...
 
 getPrimaryKeyValue ()
 Retrieves the primary key value. More...
 
 set ($field, $value)
 Set the value of the specified field. More...
 
 getType ($field)
 Retrieves the data type of the specified field. More...
 
 getHiddenFields ()
 Retrieves the list of hidden fields. More...
 
 getFilter ()
 Returns the filter set on this object. More...
 
 setFilter ($filter)
 Sets the filter on this object. More...
 
 getFieldAliases ()
 Retrieve the list of field aliases. More...
 
 getFieldAnnotations ()
 Retrieve the list of field annotations. More...
 
 load ($id)
 Load the object with the specified primary key. More...
 
 save ()
 Store the object in the database. More...
 
 select ()
 Select the object from the database, based on the value of the primary key field. More...
 
 exists ($constraint="")
 Check whether the object exists in the database. More...
 
 update ()
 Update the row in the database that corresponds to this object. More...
 
 delete ($constraint="")
 Delete the row in the database that corresponds to this object. More...
 
 deleteAll ()
 Delete all the rows in the database that correspond to this class. More...
 
 cacheLookup ($id)
 Populate the object from the local cache if the object is marked as "cacheLocal". More...
 
 quoteFieldValue ($field, $type)
 Returns the properly quoted value of the specified field. More...
 
 quoteValue ($val, $type)
 
 formatFieldValue ($field, $template="")
 
 formatFieldForXML ($field)
 Format field for XML output. More...
 
 reformatToSQLDate ($date)
 Reformats the specified date to be in a format used by the database. More...
 
 reformatFromSQLDate ($date)
 
 insert ()
 Insert a new row in the database to store this object. More...
 
 distinctValues ($field, $sorted=false, $constraint="")
 Retrieves the distinct values in the database for the specified field across the specified set of records. More...
 
 fromGET ()
 Automatically populate the object based on parameters in the $_GET collection. More...
 
 fromPOST ()
 Automatically populate the object based on parameters in the $_POST collection. More...
 
 fromREQUEST ()
 Automatically populate the object based on parameters in either the $_GET or $_POST collection, depending on the method used to access the page. More...
 
 compare ($to)
 Compare this object to another object. More...
 
 copy ($from)
 Copies values from another object, field by field. More...
 
 toXML ($indent=0, $path=null)
 Generates an XML representation of the object. More...
 
 fromXML ($node)
 Populates the object from the specified XML node. More...
 
 fromJSON ($json)
 Populate from the supplied JSON object. More...
 
 format ($template="", $separator=", ")
 
 prettifyFieldName ($field)
 
 prettifyClassName ($plural=false)
 
 relateTo ($target, $field="")
 Link this object to the specified target by setting corresponding field to the value of the target's primary key. More...
 

Static Public Member Functions

static registerEventHandler ($class, $event, $handler)
 Register an event handler for a specific event and DataItem class. More...
 

Public Attributes

 $_tx = null
 
 $_pkDisabled = false
 
- Public Attributes inherited from AbstractDataItem
 $filter
 
 $_options = 0
 
 $_tx = null
 Tracks the current database transaction for each DataItem. More...
 
 $_decorations = null
 

Static Public Attributes

static $_eventMap = array()
 
static $dataTypeRendererMap
 

Detailed Description

DataItem is the generic base class for database mapped classes.

It provides a compact, consistent API for object persistence in the database.

Definition at line 57 of file data_item.inc.

Member Function Documentation

◆ __sleep()

DataItem::__sleep ( )

Definition at line 128 of file data_item.inc.

129  {
130  // No need to persist class variables, such as field metadata
131 
132  $f = array_keys($this->getFields());
133  array_push($f, "primary_key", "table", "filter");
134  return $f;
135  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ cacheLookup()

DataItem::cacheLookup (   $id)

Definition at line 1084 of file data_item.inc.

1085  {
1086  if ($this->cacheLocal)
1087  {
1088  $cache = get_class($this)."_cache";
1089  $items = Cache::get($cache);
1090  if (!is_array($items))
1091  {
1092  $items = IndexedQuery::create(get_class($this), "", $this->primary_key)->execute();
1093  Cache::put($cache, $items);
1094  }
1095  if (array_key_exists($id, $items))
1096  {
1097  trace("Using local cache $cache for item $id", 5);
1098  $this->copy($items[$id]);
1099  return true;
1100  }
1101  }
1102 
1103  return false;
1104  }
copy($from)
Copies values from another object, field by field.
Definition: data_item.inc:1067
static get($key)
Retrieve the specified object from the cache.
Definition: cache.inc:88
static put($key, $obj, $ttl=0)
Store the specified object in the cache at the specified key.
Definition: cache.inc:106
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
static create($class, $constraints="", $indexBy="")

◆ cast()

DataItem::cast (   $class)

Cast this object to another class.

For simple DataItems this checks that the class is the same as the supplied class and returns a reference if so. If not an exception is thrown.

Parameters
string$class
Returns
instance of the specified class, if compatible
Exceptions
DataItemException

Definition at line 214 of file data_item.inc.

215  {
216  if (get_class($this) != $class)
217  {
218  throw new DataItemException("Cannot cast ".get_class($this)." to $class.");
219  }
220 
221  return $this;
222  }

◆ compare()

DataItem::compare (   $to)

Compare this object to another object.

If all the fields match, the method returns true, otherwise false. If a filter is in place on the source object, then only the filtered fields are compared.

Parameters
object$tothe object with which to compare this object

Definition at line 1046 of file data_item.inc.

1047  {
1048  foreach($this->getFields() as $field => $type)
1049  {
1050  if ($this->filter && $this->filter->isExcluded($field)) continue;
1051  if ($to->$field != $this->$field)
1052  {
1053  trace("$field '{$this->$field}' != '{$to->$field}'", 3);
1054  return false;
1055  }
1056  }
1057 
1058  return true;
1059  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ copy()

DataItem::copy (   $from)

Copies values from another object, field by field.

If a filter is in place on the source object, then only the filtered fields are copied.

Parameters
objectfrom the object from which data is to be copied

Definition at line 1067 of file data_item.inc.

1068  {
1069  foreach($this->getFields() as $field => $type)
1070  {
1071  if ($this->filter && $this->filter->isExcluded($field)) continue;
1072  $this->$field = $from->$field;
1073  }
1074 
1075  if (is_array($this->calculatedFields))
1076  {
1077  foreach($this->calculatedFields as $field => $expr)
1078  {
1079  $this->$field = $from->$field;
1080  }
1081  }
1082  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ crossReference()

DataItem::crossReference (   $class,
  $xref,
  $orderBy = "",
  $pkField = "",
  $xrefField = "" 
)

Returns a list of items related to this item via a cross-reference table.

The cross-reference table must contain the primary keys of each of the related classes as fields.

Parameters
string$classthe name of the related class
string$xrefthe name of the cross-reference table
string$orderBy(optional) a sort order clause for the results.

Definition at line 1187 of file data_item.inc.

1188  {
1189  $obj = new $class;
1190  $xref = new $xref;
1191 
1192  if ($orderBy != "")
1193  {
1194  foreach($obj->getFields() as $field => $type)
1195  {
1196  $orderBy = preg_replace("/\\b".$field."\\b/i", "a0.$field", $orderBy);
1197  }
1198  }
1199 
1200  $orderBy = preg_replace("/^\s*WHERE\s+/i", "AND ", $orderBy);
1201 
1202  $xt = $xref->table;
1203  $xp = ($xrefField != "") ? $xrefField : $obj->primary_key;
1204 
1205  $pkField = ($pkField != "") ? $pkField : $this->primary_key;
1206  $pk = $this->primary_key;
1207 
1208  $fieldList = $obj->getFieldList("a0");
1209 
1210  $query = "SELECT {$fieldList} FROM {$obj->table} a0, $xt x WHERE a0.{$obj->primary_key}=x.{$xp} AND x.{$pkField}={$this->$pk} $orderBy";
1211 
1212  trace($query, 3);
1213 
1214  try
1215  {
1216  $db = $this->getConnection();
1217 
1218  $result = $db->prepare($query);
1219  $result->execute();
1220 
1221  $list = array();
1222  while ($line = $result->fetch())
1223  {
1224  $obj = new $class;
1225  $obj->populate($line, "a0");
1226  $list[] = $obj;
1227  }
1228 
1229  unset($result);
1230  }
1231  catch(PDOException $e)
1232  {
1233  $err = "DataItem::crossReference() failed - " . $e->getMessage();
1234  trace($err, 2);
1235  throw new DataItemException($err);
1236  }
1237  return $list;
1238  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.

◆ DataItem()

DataItem::DataItem ( )

Constructor.

DataItems can be constructed in three ways:

  1. Empty objects can be constructed by calling the constructor with no arguments
  2. Objects can be instantiated from their primary key by passing in a single value
  3. Objects can be populated from an associative array of field/value pairs [such as those returned from mysql_fetch_assoc()]

Definition at line 92 of file data_item.inc.

93  {
94  if (func_num_args() > 0)
95  {
96  $arg = func_get_arg(0);
97 
98  if (is_array($arg) )
99  {
100  if (count($arg) > 1)
101  {
102  $this->populate($arg);
103  }
104  else if (count($arg) > 0)
105  {
106  if (is_array($arg[0]))
107  {
108  $this->populate($arg[0]);
109  }
110  else
111  {
112  $this->load($arg[0]);
113  }
114  }
115  }
116  else
117  {
118  if (func_num_args() > 1)
119  {
120  $this->filter = func_get_arg(1);
121  }
122 
123  $this->load($arg);
124  }
125  }
126  }
load($id)
Load the object with the specified primary key.
Definition: data_item.inc:536
populate($line, $alias=false)
Populates the object using the supplied associative array (field -> value).
Definition: data_item.inc:257

◆ delete()

DataItem::delete (   $constraint = "")

Delete the row in the database that corresponds to this object.

Definition at line 833 of file data_item.inc.

834  {
835  if ($constraint == "")
836  {
837  $fire = true;
838  $pk = $this->primary_key;
839  $constraint = "WHERE $pk={$this->$pk} ".$this->getIdentityConstraint();
840  }
841 
842  $query = "DELETE FROM {$this->table} $constraint";
843 
844  trace($query, 3);
845 
846  $db = $this->getConnection();
847 
848  try
849  {
850  if ($fire) $this->fireEvent("onPreDelete");
851  $db->exec($query);
852  if ($fire) $this->fireEvent("onPostDelete");
853  }
854  catch(PDOException $e)
855  {
856  $err = "DataItem::delete() failed - " . $e->getMessage();
857  trace($err, 2);
858  throw new DataItemException($err);
859  }
860  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.
fireEvent($event)
Fires the specified event to all registered handlers.
Definition: data_item.inc:164

◆ deleteAll()

DataItem::deleteAll ( )

Delete all the rows in the database that correspond to this class.

Definition at line 865 of file data_item.inc.

866  {
867  $query = "TRUNCATE TABLE {$this->table}";
868  $db = $this->getConnection();
869 
870  trace($query, 3);
871 
872  try
873  {
874  $db->exec($query);
875  $this->fireEvent("onDeleteAll");
876  }
877  catch(PDOException $e)
878  {
879  $err = "DataItem::deleteAll() failed - " . $e->getMessage();
880  trace($err, 2);
881  throw new DataItemException($err);
882  }
883  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.
fireEvent($event)
Fires the specified event to all registered handlers.
Definition: data_item.inc:164

◆ disablePrimaryKey()

DataItem::disablePrimaryKey ( )

Definition at line 224 of file data_item.inc.

225  {
226  if (!$this->_disablePK)
227  {
228  $conn = $this->getConnection();
229  $conn->prepare("ALTER TABLE `{$this->table}` DISABLE KEYS")->execute();
230  $this->_disablePK = true;
231  }
232  }
getConnection()
Retrieves a connection to the database.

◆ distinctValues()

DataItem::distinctValues (   $field,
  $sorted = false,
  $constraint = "" 
)

Retrieves the distinct values in the database for the specified field across the specified set of records.

Parameters
string$field
boolean$sorted
string$constraint
Returns
array

Definition at line 926 of file data_item.inc.

927  {
928  $query = "SELECT DISTINCT $field from {$this->table} $constraint";
929 
930  trace($query, 3);
931 
932  $db = $this->getConnection();
933 
934  try
935  {
936  $result = $db->prepare($query);
937  $result->execute();
938 
939  $values = array();
940 
941  while($line = $result->fetch())
942  {
943  $values[] = $line[$field];
944  }
945 
946  if ($sorted)
947  {
948  sort($values);
949  }
950 
951  unset($result);
952 
953  return $values;
954  }
955  catch(PDOException $e)
956  {
957  $err = "DataItem::distinctValues() failed - " . $e->getMessage();
958  trace($err, 2);
959  throw new DataItemException($err);
960  }
961 
962  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.

◆ enablePrimaryKey()

DataItem::enablePrimaryKey ( )

Definition at line 234 of file data_item.inc.

235  {
236  if ($this->_disablePK)
237  {
238  $conn = $this->getConnection();
239  $conn->prepare("ALTER TABLE `{$this->table}` ENABLE KEYS")->execute();
240  $this->_disablePK = false;
241  }
242  }
getConnection()
Retrieves a connection to the database.

◆ exists()

DataItem::exists (   $constraint = "")

Check whether the object exists in the database.

Definition at line 618 of file data_item.inc.

619  {
620 
621  $pk = $this->primary_key;
622 
623  if (!$constraint)
624  {
625  if ($this->$pk == "" || $this->$pk == 0) return false;
626  $constraint = "WHERE $pk={$this->$pk}";
627  }
628 
629  $query = "SELECT $pk FROM {$this->table} $constraint";
630  trace("DataItem::exists() - $query", 3);
631 
632  $db = $this->getConnection();
633  $exists = false;
634 
635  try
636  {
637  $result = $db->prepare($query);
638  $result->execute();
639 
640  if ($line = $result->fetch())
641  {
642  $exists = true;
643  }
644 
645  unset($result);
646  }
647  catch(PDOException $e)
648  {
649  $err = "DataItem::exists() failed - " . $e->getMessage();
650  trace($err, 2);
651  throw new DataItemException($err);
652  }
653 
654  return $exists;
655  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.

◆ fireEvent()

DataItem::fireEvent (   $event)

Fires the specified event to all registered handlers.

The firing object is passed as a parameter to all the registered handlers.

Parameters
string$eventthe event to be fired

Definition at line 164 of file data_item.inc.

165  {
166  $eventKey = get_class($this)."_{$event}";
167  if (!array_key_exists($eventKey, DataItem::$_eventMap))
168  {
169  return;
170  }
171 
172  trace("===== DataItem event key = $eventKey", 3);
173  $handlers = DataItem::$_eventMap[$eventKey];
174 
175  if (!is_array($handlers)) return;
176  foreach($handlers as $handler)
177  {
178  if (!is_callable($handler))
179  {
180  trace(get_class($this)." {$event} handler is invalid", 2);
181  }
182  else
183  {
184  call_user_func_array($handler, array($this));
185  }
186  }
187  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
static $_eventMap
Definition: data_item.inc:59

◆ format()

DataItem::format (   $template = "",
  $separator = ", " 
)

Substitute values for field names in a string, with the fields formatted using their type's default format or according to the formatting template sting passed in.

example template string: "{program_name} {start_date} {number_students}"

  1. data type format specifications: The start_date field can have formatting specifications such as "{start_date:long} for long format. For more information on formatting specifications following the colon, check comments in DataTypeRenderer classes.
  2. Default value specification: syntax: {field|alternate} example: {name|N/A}

In the above example "N/A" would be output if the name field is empty or null. This will also work with numeric fields with a value of 0 and booleans with false. Very useful for places where you are linking to a form by name or title.

  1. Inline static method call: syntax: {class::method} example: {MyHelper::getComplicatedOutput} This works the same as passing array(MyHelper, getComplicatedOutput) to a DataListView. It calls the static method getComplicatedOutput() on the MyHelper class, passing the current object in as a parameter. The new inline format means that you can use it as part of more complicated expressions like: "{name} - {MyHelper::getComplicatedOutput}"
  2. Retrieve field value through relations.

Fields can also be retrieved through a relation from the dataitem obj that calls this format function.

  1. Local method calls

Syntax: {method()} Example: {getFullName()}

This format calls the specified method on the object and substitutes the returned value into the output. Parameters cannot be passed.

for example: "{MyRelation.event_name}"

Variables used: $format - stores the pattern inside the braces {} for search & replace substitution in the template string.

$fieldFormat - the requested formatting for the field, if any.

$sub - the value to be substituted or replacement value in the tempalte string.

Definition at line 1483 of file data_item.inc.

1484  {
1485  if ($template == "") $template = $this->default_format;
1486  if (is_array($template) && is_callable($template))
1487  {
1488  return call_user_func($template, $this);
1489  }
1490 
1491  foreach($this->getFields() as $field => $type)
1492  {
1493  $template = str_replace("{".$field."}", $this->formatFieldValue($field), $template);
1494  }
1495 
1496  if (isset($this->calculatedFields))
1497  {
1498  foreach($this->calculatedFields as $field => $expr)
1499  {
1500  $template = str_replace("{".$field."}", $this->$field, $template);
1501  }
1502  }
1503 
1504  if (isset($this->_decorations))
1505  {
1506  foreach($this->_decorations as $field => $value)
1507  {
1508  $template = str_replace("{".$field."}", $value, $template);
1509  }
1510  }
1511 
1512  // Allow drill-down through relation functions
1513  $template = $this->formatThroughRelation($template, $separator);
1514 
1515  $template = $this->formatField($template);
1516 
1517  // Simple method calls - no parameter passing
1518  // ??Is this block ever executed??
1519 
1520  $matches = array();
1521  preg_match_all("/\\{([\\w_]+)\\(\\)\\}/", $template, $matches, PREG_SET_ORDER);
1522 
1523  foreach($matches as $match)
1524  {
1525  $format = $match[0];
1526  $method = $match[1];
1527 
1528  $value = $this->$method();
1529 
1530  $template = str_replace($format, $value, $template);
1531  }
1532 
1533  return $template;
1534  }
formatThroughRelation($template, $separator=", ")
Definition: data_item.inc:1614
formatField($template)
Definition: data_item.inc:1544
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ formatField()

DataItem::formatField (   $template)

Definition at line 1544 of file data_item.inc.

1545  {
1546  $matches = array();
1547 
1548  preg_match_all("/\\{([\\w\\d_]+)(::?|\\^|\\(\\)|\\|)?([^}]*)}/", $template, $matches, PREG_SET_ORDER);
1549 
1550  foreach($matches as $match)
1551  {
1552  $field = $match[1];
1553  // JDG 3/12 fix issue with call to function in DataItem in format like "{getTitle()}" with no separator;
1554  $separator = ($match[2]) ? $match[2] : ":";
1555 
1556  $fieldFormat = $match[3];
1557  trace("formatField, template $template, field $field, separator $separator and fieldFormat $fieldFormat", 5);
1558 
1559  $format = "{".$field.$separator.$fieldFormat."}";
1560 
1561  switch($separator)
1562  {
1563  case "|":
1564  if (!$this->get($field))
1565  {
1566  $sub = $fieldFormat;
1567  }
1568  else
1569  {
1570  $sub = $this->formatFieldValue($field);
1571  }
1572  break;
1573 
1574  case "^":
1575  if (!$this->get($field))
1576  {
1577  $sub = $this->format("{".$fieldFormat."}");
1578  }
1579  else
1580  {
1581  $sub = $this->formatFieldValue($field);
1582  }
1583  break;
1584 
1585  case "::":
1586 
1587  $sub = call_user_func(array($field, $fieldFormat), $this);
1588  break;
1589 
1590  case "()":
1591 
1592  $sub = $this->$field();
1593  break;
1594 
1595  case ":":
1596  default:
1597  $sub = $this->formatFieldValue($field, $fieldFormat);
1598  }
1599 
1600  $template = str_replace($format, $sub, $template);
1601  }
1602  return $template;
1603  }
formatFieldValue($field, $template="")
format($template="", $separator=", ")
Substitute values for field names in a string, with the fields formatted using their type's default f...
Definition: data_item.inc:1483
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ formatThroughRelation()

DataItem::formatThroughRelation (   $template,
  $separator = ", " 
)

Definition at line 1614 of file data_item.inc.

1615  {
1616  $matches = array();
1617  preg_match_all("/\\{([\\w\\d_]+)\\.([\\w\\d_\\.\\(\\)]+):?([^}]*)}/", $template, $matches, PREG_SET_ORDER);
1618 
1619  foreach($matches as $match)
1620  {
1621  $relation = $match[1];
1622  $field = $match[2];
1623 
1624  if(count($match) == 4 && preg_match("/^where|order/i", $match[3]))
1625  $constraint = $match[3];
1626  elseif(count($match) == 4)
1627  $fieldTemplate = $match[3];
1628 
1629  trace("function format: formatThroughRelations template $template field $field relation $relation constraint $constraint", 5);
1630 
1631  if ($constraint)
1632  {
1633  $relations = $this->$relation($constraint);
1634  $format = "{".$relation.".".$field.":".$constraint."}";
1635  }
1636  elseif($fieldTemplate)
1637  {
1638  $relations = $this->$relation();
1639  $format = "{".$relation.".".$field.":".$fieldTemplate."}";
1640  }
1641  else
1642  {
1643  $relations = $this->$relation();
1644  $format = "{".$relation.".".$field."}";
1645  }
1646 
1647  $sub = "";
1648 
1649  if (is_array($relations))
1650  {
1651  $formatTemplate = ($fieldTemplate) ? "{".$field .":".$fieldTemplate . "}" : "{".$field."}";
1652  $sub = formatItems($relations, $formatTemplate, $separator);
1653 
1654  }
1655  else if ($relations)
1656  {
1657  if ($fieldTemplate) $fieldTemplate = ":{$fieldTemplate}";
1658  if ($relations) $sub = $relations->format("{{$field}{$fieldTemplate}}");
1659  }
1660 
1661  trace("format using relations: Replacing {$match[0]} [ $format ] with '$sub'", 5);
1662 
1663  $template = str_replace($format, $sub, $template);
1664  }
1665 
1666  return $template;
1667  }
formatItems($items, $template, $separator="")
Format a list of DataItems using the specified templated.
Definition: data_item.inc:2031
format($template="", $separator=", ")
Substitute values for field names in a string, with the fields formatted using their type's default f...
Definition: data_item.inc:1483
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ fromDataSet()

DataItem::fromDataSet (   $params)

Automatically populate the object based on a custom set of parameters (such as a filtered $_POST collection)

Definition at line 1023 of file data_item.inc.

1024  {
1025  foreach($this->getFields() as $field => $type)
1026  {
1027  if ($this->filter && $this->filter->isExcluded($field)) continue;
1028  if (array_key_exists($field, $params))
1029  {
1030  $this->$field = $params[$field];
1031  }
1032  elseif (!array_key_exists($field, $params) AND ($type == Boolean))
1033  {
1034  $this->$field = 0;
1035  }
1036  }
1037  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ fromGET()

DataItem::fromGET ( )

Automatically populate the object based on parameters in the $_GET collection.

Definition at line 967 of file data_item.inc.

968  {
969  foreach($this->getFields() as $field => $type)
970  {
971  if ($this->filter && $this->filter->isExcluded($field)) continue;
972  if (array_key_exists($field, $_GET))
973  {
974  $this->set($field, $_GET[$field]);
975  }
976  }
977  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ fromPOST()

DataItem::fromPOST ( )

Automatically populate the object based on parameters in the $_POST collection.

If the key does not exist in $_POST and the type is Boolean, that means that the user unchecked a checkbox and we need to assign 0 to the field.

Definition at line 985 of file data_item.inc.

986  {
987  foreach($this->getFields() as $field => $type)
988  {
989  if ($this->filter && $this->filter->isExcluded($field)) continue;
990  if (array_key_exists($field, $_POST))
991  {
992  $this->set($field, $_POST[$field]);
993  }
994  elseif (!array_key_exists($field, $_POST) AND ($type == Boolean))
995  {
996  $this->$field = 0;
997  }
998  }
999  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ fromREQUEST()

DataItem::fromREQUEST ( )

Automatically populate the object based on parameters in either the $_GET or $_POST collection, depending on the method used to access the page.

Definition at line 1005 of file data_item.inc.

1006  {
1007  switch($_SERVER["REQUEST_METHOD"])
1008  {
1009  case "POST":
1010  $this->fromPOST();
1011  break;
1012 
1013  case "GET":
1014  default:
1015  $this->fromGET();
1016  }
1017  }
fromPOST()
Automatically populate the object based on parameters in the $_POST collection.
Definition: data_item.inc:985
fromGET()
Automatically populate the object based on parameters in the $_GET collection.
Definition: data_item.inc:967

◆ fromXML()

DataItem::fromXML (   $node)

Definition at line 1386 of file data_item.inc.

1387  {
1388  if ($node->nodeType != XML_ELEMENT_NODE || $node->tagName != get_class($this)) return;
1389 
1390  $kids = $node->childNodes;
1391  $numChildren = $kids->length;
1392 
1393  for($i = 0; $i < $numChildren; ++$i)
1394  {
1395  $n = $kids->item($i);
1396 
1397  if ($n->nodeType != XML_ELEMENT_NODE) continue;
1398  $field = $n->tagName;
1399  $this->set($field, $n->nodeValue);
1400  }
1401  }

◆ get()

DataItem::get (   $field)

Retrieve the value for the specified field.

Parameters
string$fieldthe field to retrieve
Returns
mixed the value of that field

Definition at line 468 of file data_item.inc.

469  {
470  if (!$field) throw new FakoliException("Cannot access empty field");
471  return $this->$field;
472  }

◆ getFieldAliases()

DataItem::getFieldAliases ( )

Retrieve the list of field aliases.

Returns
array the alias list for this object

Definition at line 517 of file data_item.inc.

518  {
519  return $this->fieldAliases;
520  }

◆ getFieldAnnotations()

DataItem::getFieldAnnotations ( )

Retrieve the list of field annotations.

Returns
array the annotation list for this object

Definition at line 526 of file data_item.inc.

527  {
528  return $this->fieldAnnotations;
529  }

◆ getFieldArray()

DataItem::getFieldArray ( )

Return an array of field names for this object filtered by any active filter.

Returns
array

Definition at line 409 of file data_item.inc.

410  {
411  $arr = array();
412  foreach($this->getFields() as $field => $type)
413  {
414  if ($this->filter && $this->filter->isExcluded($field)) continue;
415  $arr[] = $field;
416  }
417 
418  return $arr;
419  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ getFieldList()

DataItem::getFieldList (   $alias = "")

Returned a comma-separated list of the fields for this object (applying the assigned filter if there is one).

Definition at line 355 of file data_item.inc.

356  {
357  $list = "";
358  $first = true;
359 
360  foreach($this->getFields() as $field => $type)
361  {
362  if ($this->filter && $this->filter->isExcluded($field)) continue;
363  if (!$first) $list .= ", ";
364  if ($alias)
365  {
366  $list .= "$alias.";
367  }
368  $list .= $field;
369  if ($alias)
370  {
371  $list .= " as `$alias.$field`";
372  }
373  $first = false;
374  }
375 
376  if (isset($this->calculatedFields))
377  {
378  foreach($this->calculatedFields as $field => $expr)
379  {
380  if ($this->filter && $this->filter->isExcluded($field)) continue;
381  if (!$first) $list .= ", ";
382 
383  if ($alias)
384  {
385  foreach($this->getFields() as $f => $type)
386  {
387  $expr = preg_replace('/([\s\(])('.$f.')\b/', "$1{$alias}.$2", $expr);
388  $expr = preg_replace('/\b'.$this->table.'\.'.$f.'\b/', "{$alias}.{$f}", $expr);
389  }
390  }
391 
392  $list .= $expr . " as `";
393  if ($alias)
394  {
395  $list .= $alias.".";
396  }
397  $list .= $field."`";
398 
399  }
400  }
401 
402  return $list;
403  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ getFields()

DataItem::getFields ( )

Retrieve the field type list for this object.

Definition at line 327 of file data_item.inc.

328  {
329  if ($this->fields) return $this->fields;
330  $class = get_class($this);
331  if ($class::$fields) return $class::$fields;
332 
333  throw new FakoliException("DataItem does not contain any fields");
334  }

◆ getFilter()

DataItem::getFilter ( )

Returns the filter set on this object.

Definition at line 499 of file data_item.inc.

500  {
501  return $this->filter;
502  }

◆ getHiddenFields()

DataItem::getHiddenFields ( )

Definition at line 244 of file data_item.inc.

245  {
246  return $this->hiddenFields;
247  }

◆ getPrimaryKey()

DataItem::getPrimaryKey ( )

Retrieves the primary key field name.

Definition at line 449 of file data_item.inc.

450  {
451  return $this->primary_key;
452  }

◆ getPrimaryKeyList()

DataItem::getPrimaryKeyList ( )

Retrieves a list of all the primary keys used for an object as an array.

Returns
array all the primary keys for this object's constituent parts

Definition at line 458 of file data_item.inc.

459  {
460  return array($this->primary_key);
461  }

◆ getRelated()

DataItem::getRelated (   $class,
  $field = "" 
)

Returns a single item related by the specified foreign key.

The foreign key name must match the primary key name for the specified class.

Use this method to implement one-to-one relations.

Parameters
string$classthe name of the related class
string$fieldthe name of the foreign key defining the relation.

Definition at line 1115 of file data_item.inc.

1116  {
1117  $obj = new $class;
1118  if ($field == "")
1119  {
1120  $field = $obj->primary_key;
1121 
1122  }
1123 
1124  if (array_key_exists($field, $this->getFields()))
1125  {
1126  $pk = $obj->primary_key;
1127  $val = $this->get($field);
1128 
1129  if (!$val) return null;
1130 
1131  $obj->$pk = $val;
1132 
1133  $cache = "_{$class}_{$field}_{$val}";
1134  if (isset($this->$cache))
1135  {
1136  $obj->copy($this->$cache);
1137  }
1138  else
1139  {
1140  $obj->select();
1141  $this->$cache = $obj;
1142  }
1143  }
1144  else
1145  {
1146  $field = $this->primary_key;
1147  $obj = querySingle($class, "WHERE $field={$this->$field}");
1148  }
1149  return $obj;
1150  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327
querySingle($class)
Performs a query against the database and returns a matching singleton object.
Definition: data_item.inc:1711

◆ getRelatedList()

DataItem::getRelatedList (   $class,
  $field = "",
  $orderBy = "" 
)

Returns a list of items that are related to this item.

Usually the items will be related by having a foreign key field that matches the primary key on the calling object. However, another field on the calling object can be specified if required. You can also optionally specify a sort order for the results.

Use this field to implement one-to-many relationships.

Parameters
string$classthe name of the related class
string$field(optional) the name of the field defining the relation
string$orderBy(optional) a sort order clause for the results

Definition at line 1165 of file data_item.inc.

1166  {
1167  $pk = $this->primary_key;
1168 
1169  if ($field == "") $field = $pk;
1170  $value = $this->$field ? $this->$field : $this->$pk;
1171  $orderBy = preg_replace("/^\s*WHERE\s+/i", "AND ", $orderBy);
1172  //$this->quoteFieldValue($this->$field, $this->fields[$field])
1173  $list = query($class, "WHERE $field=$value $orderBy");
1174 
1175  return $list;
1176  }
query($class)
Performs a query against the database, returning an array of DataItem objects of the specified class...
Definition: query.inc:360

◆ getTransaction()

DataItem::getTransaction ( )

Retrieves the current DataTransaction.

Definition at line 201 of file data_item.inc.

202  {
203  return $this->_tx;
204  }

◆ getType()

DataItem::getType (   $field)

Retrieves the data type of the specified field.

Parameters
$fieldthe field in question
Returns
string the data type of the specified field

Definition at line 490 of file data_item.inc.

491  {
492  $fields = $this->getFields();
493  return $fields[$field];
494  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ hasField()

DataItem::hasField (   $field)

Returns true if this DataItem contains a field with the specified name and that field is not excluded by a filter.

Parameters
string$field
Returns
true if this field is present and not filtered, false otherwise.

Definition at line 428 of file data_item.inc.

429  {
430  if (!array_key_exists($field, $this->getFields())) return false;
431  if ($this->filter && $this->filter->isExcluded($field)) return false;
432  return true;
433  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327

◆ hasRelation()

DataItem::hasRelation (   $relation)

Returns true if this DataItem contains a relation with the specified name.

Parameters
string$relation
Returns
true if this relation is present and not filtered, false otherwise.

Definition at line 441 of file data_item.inc.

442  {
443  return (!array_key_exists($relation, $this->relations)) ? false : true;
444  }

◆ insert()

DataItem::insert ( )

Insert a new row in the database to store this object.

Definition at line 761 of file data_item.inc.

762  {
763  $pk = $this->primary_key;
764 
765  $first = true;
766 
767  $timestampField = null;
768 
769  foreach($this->getFields() as $field => $type)
770  {
771  if ($field == $pk && !$this->_disablePK) continue;
772  if ($this->filter && $this->filter->isExcluded($field)) continue;
773  if (!isset($this->$field) && $this->getType($field) != Timestamp && $this->getType($field) != Boolean) continue;
774 
775  if ($type == Timestamp)
776  {
777  $timestampField = $field;
778  }
779 
780  if (!$first)
781  {
782  $fields .= ", ";
783  $values .= ", ";
784  }
785 
786  $fields .= $field;
787  $values .= $this->quoteFieldValue($field, $type);
788 
789  $first = false;
790  }
791 
792  $query = "INSERT INTO {$this->table} ($fields) values ($values)";
793 
794  trace("DataItem::insert() - $query", 3);
795 
796  $success = false;
797 
798  try
799  {
800  $db = $this->getConnection();
801  $success = $db->exec($query);
802 
803  if ($success !== FALSE)
804  {
805  $this->$pk = $db->lastInsertId();
806  //AJG - Set the timestamp field value if the insert succeeded
807  if ($timestampField)
808  {
809  $this->$timestampField = $this->__timestamp;
810  unset($this->__timestamp);
811  }
812 
813  $this->fireEvent("onInsert");
814  }
815  else
816  {
817  $this->$pk = 0;
818  trace("DataItem::insert() failed - $query", 2);
819  }
820  }
821  catch(PDOException $e)
822  {
823  $err = "DataItem::insert() failed - ". $e->getMessage();
824  trace($err, 2);
825  throw new DataItemException($err);
826  }
827  return $success;
828  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327
getConnection()
Retrieves a connection to the database.
fireEvent($event)
Fires the specified event to all registered handlers.
Definition: data_item.inc:164
getType($field)
Retrieves the data type of the specified field.
Definition: data_item.inc:490
quoteFieldValue($field, $type)
Returns the properly quoted value of the specified field.

◆ joinTransaction()

DataItem::joinTransaction (   $tx)

Join the DataItem to the specified DataTransaction.

Parameters
DataTransaction$txthe transaction to join

Definition at line 193 of file data_item.inc.

194  {
195  $this->_tx = $tx;
196  }

◆ load()

DataItem::load (   $id)

Load the object with the specified primary key.

Parameters
intid the primary key value to instantiate from

Definition at line 536 of file data_item.inc.

537  {
538  if ($this->cacheLookup($id)) return;
539 
540  $fields = $this->getFieldList();
541  $query = "SELECT $fields FROM {$this->table} WHERE {$this->primary_key}=$id ".$this->getIdentityConstraint();
542  trace("DataItem::load($id): $query", 3);
543 
544  $db = $this->getConnection();
545 
546  try
547  {
548  $result = $db->prepare($query);
549  $result->execute();
550 
551  if ($line = $result->fetch())
552  {
553  $this->populate($line);
554  }
555 
556  unset($result);
557  }
558  catch(PDOException $e)
559  {
560  $err = "DataItem::load() failed - ".$e->getMessage();
561  trace($err, 2);
562  throw new DataItemException($err);
563  }
564  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.
populate($line, $alias=false)
Populates the object using the supplied associative array (field -> value).
Definition: data_item.inc:257
cacheLookup($id)
Definition: data_item.inc:1084
getFieldList($alias="")
Returned a comma-separated list of the fields for this object (applying the assigned filter if there ...
Definition: data_item.inc:355

◆ loadComposite()

DataItem::loadComposite ( )

Creates an outer CompositeDataItem from its base component.

In order for this method to succeed, the base component table must have a 'composite_class' field that is populated with the class name of the correct CompositeDataItem class.

Returns
the containing CompositeDataItem for this base component.

Definition at line 573 of file data_item.inc.

574  {
575  if (!$this->hasField("composite_class") || !$this->composite_class)
576  {
577  throw new DataItemException("Cannot create composite from ".get_class($this)." as required composite cannot be determined");
578  }
579 
580  $composite = new $this->composite_class;
581  $composite->loadFromBase($this->get($this->getPrimaryKey()));
582 
583  return $composite;
584  }
hasField($field)
Returns true if this DataItem contains a field with the specified name and that field is not excluded...
Definition: data_item.inc:428
getPrimaryKey()
Retrieves the primary key field name.
Definition: data_item.inc:449

◆ overrideFieldType()

DataItem::overrideFieldType (   $field,
  $type 
)

Override the type for the specified field.

Parameters
string$field
string$type

Definition at line 341 of file data_item.inc.

342  {
343  if (!is_array($this->fields))
344  {
345  throw new FakoliException("Cannot override field types for statically defined DataItems");
346  }
347 
348  $this->fields[$field] = $type;
349  }

◆ populate()

DataItem::populate (   $line,
  $alias = false 
)

Populates the object using the supplied associative array (field -> value).

Only values that match the definition of the sub-classed object will be copied. Fields that have been excluded by the use of an InclusionFilter or ExclusionFilter will also not be populated.

Parameters
array$linethe array of values to populate the object with.

Definition at line 257 of file data_item.inc.

258  {
259  global $config;
260 
261  // NOTE - structured for speed, since the general case is no aliasing
262  // therefore we want to reduce the number of tests of the alias
263 
264  $fields = $this->getFields();
265 
266  if ($alias)
267  {
268  $offset = strlen($alias) + 1;
269 
270  foreach ($line as $field => $value)
271  {
272  if (!startsWith($field, $alias)) continue;
273  $field = substr($field, $offset);
274 
275  if (!array_key_exists($field, $fields)) continue;
276  if ($this->filter && $this->filter->isExcluded($field)) continue;
277 
278  if ($config["no_charset_conversions"])
279  {
280  $this->$field = $value;
281  }
282  else
283  {
284  $this->$field = iconv("UTF-8", "CP1252//IGNORE", $value);
285  }
286  }
287  }
288  else
289  {
290  foreach ($line as $field => $value)
291  {
292  if (!array_key_exists($field, $fields)) continue;
293  if ($this->filter && $this->filter->isExcluded($field)) continue;
294 
295  if ($config["no_charset_conversions"])
296  {
297  $this->$field = $value;
298  }
299  else
300  {
301  $this->$field = iconv("UTF-8", "CP1252//IGNORE", $value);
302  }
303  }
304  }
305 
306  if (isset($this->calculatedFields))
307  {
308  foreach($this->calculatedFields as $field => $expr)
309  {
310  if ($alias)
311  {
312  $this->$field = $line[$alias.".".$field];
313  }
314  else
315  {
316  $this->$field = $line[$field];
317  }
318  }
319  }
320 
321  $this->fireEvent("onPopulate");
322  }
startsWith($text, $start)
Tests whether a string starts with a given sub-string.
Definition: functions.inc:1419
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327
fireEvent($event)
Fires the specified event to all registered handlers.
Definition: data_item.inc:164

◆ prettifyFieldName()

DataItem::prettifyFieldName (   $field)

Definition at line 1670 of file data_item.inc.

1671  {
1672  if (isset($this->fieldAliases) && array_key_exists($field, $this->fieldAliases))
1673  {
1674  return $this->fieldAliases[$field];
1675  }
1676 
1677  $field = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $field);
1678  $field = str_replace("_", " ", $field);
1679  $field = ucwords($field);
1680 
1681  return $field;
1682  }

◆ queryValue()

DataItem::queryValue (   $func)

Query the database to calculate an aggregate value.

The database table associated with the instatiated object is used as the source for the data.

Parameters
string$functhe value or function to retrieve
string$constraintsoptional constraint clause to apply to the query

Definition at line 1247 of file data_item.inc.

1248  {
1249  $constraints = "";
1250  $value = null;
1251 
1252  if (func_num_args() > 1)
1253  {
1254  $constraints = func_get_arg(1);
1255 
1256  if (func_num_args() > 2)
1257  {
1258  $value = func_get_arg(2);
1259  }
1260  }
1261 
1262  if ($constraints == "") $constraints = "WHERE 1=1"; //TODO - tidy this up some day
1263  $constraints .= " ".$this->getIdentityConstraint();
1264 
1265  $query = "SELECT $func as result FROM {$this->table} $constraints";
1266 
1267  trace("DataItem::queryValue: $query", 3);
1268  try
1269  {
1270  $db = $this->getConnection();
1271  $result = $db->prepare($query);
1272  $result->execute();
1273 
1274  if ($row =$result->fetch())
1275  {
1276  $value = $row['result'];
1277  }
1278 
1279  unset($result);
1280  }
1281  catch(PDOException $e)
1282  {
1283  $err = "DataItem::queryValue() failed - " . $e->getMessage();
1284  trace($err, 2);
1285  throw new DataItemException($err);
1286  }
1287 
1288  return $value;
1289 
1290  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.

◆ registerEventHandler()

static DataItem::registerEventHandler (   $class,
  $event,
  $handler 
)
static

Register an event handler for a specific event and DataItem class.

DataItem events are fired by DataItems at various points in the data lifecycle (such as inserting, updating, deleting, etc.)

Parameters
string$classthe DataItem class to which the event handler is to be attached
string$eventthe name of the event
callable$handlerthe event handler (a callable function)

Definition at line 146 of file data_item.inc.

147  {
148  $eventKey = "{$class}_{$event}";
149 
150  if (!array_key_exists($eventKey, DataItem::$_eventMap))
151  {
152 
153  DataItem::$_eventMap[$eventKey]= array();
154  }
155 
156  array_push(DataItem::$_eventMap[$eventKey], $handler);
157  }
static $_eventMap
Definition: data_item.inc:59

◆ relateTo()

DataItem::relateTo (   $target,
  $field = "" 
)

Link this object to the specified target by setting corresponding field to the value of the target's primary key.

Parameters
DataItem$targetthe DataItem to which the relationship will be created
string$fieldthe field to set for the relationship. If not specified, the primary key of the target object is used for the foreign key field name.

Definition at line 1692 of file data_item.inc.

1693  {
1694  $pk = $target->primary_key;
1695 
1696  if (!$field) $field = $pk;
1697 
1698  $this->$field = $target->$pk;
1699  }

◆ save()

DataItem::save ( )

Store the object in the database.

Definition at line 589 of file data_item.inc.

590  {
591  if ($this->cacheLocal)
592  {
593  Cache::invalidate(get_class($this)."_cache");
594  }
595 
596  if ($this->exists())
597  {
598  return $this->update();
599  }
600  else
601  {
602  return $this->insert();
603  }
604  }
update()
Update the row in the database that corresponds to this object.
Definition: data_item.inc:660
insert()
Insert a new row in the database to store this object.
Definition: data_item.inc:761
exists($constraint="")
Check whether the object exists in the database.
Definition: data_item.inc:618
static invalidate($key)
Invalidates the specifed entry in the cache.
Definition: cache.inc:119

◆ select()

DataItem::select ( )

Select the object from the database, based on the value of the primary key field.

Definition at line 609 of file data_item.inc.

610  {
611  $pk = $this->primary_key;
612  $this->load($this->$pk);
613  }
load($id)
Load the object with the specified primary key.
Definition: data_item.inc:536

◆ set()

DataItem::set (   $field,
  $value 
)

Set the value of the specified field.

Parameters
$fieldthe field to set
$valuethe value to which the field is to be set

Definition at line 479 of file data_item.inc.

480  {
481  if (!$field) throw new FakoliException("Cannot access empty field");
482  $this->$field = $value;
483  }

◆ setFilter()

DataItem::setFilter (   $filter)

Sets the filter on this object.

Parameters
$filterthe filter

Definition at line 508 of file data_item.inc.

509  {
510  $this->filter = $filter;
511  }

◆ tableExists()

DataItem::tableExists ( )

Check if the table for this class exists in the database.

Definition at line 888 of file data_item.inc.

889  {
890  $query = "SHOW TABLES LIKE '{$this->table}'";
891  $db = $this->getConnection();
892 
893  trace($query, 3);
894 
895  $exists = false;
896 
897  try
898  {
899  $result = $db->prepare($query);
900  $result->execute();
901 
902  if ($line = $result->fetch())
903  {
904  $exists = true;
905  }
906 
907  unset($result);
908  }
909  catch(PDOException $e)
910  {
911  $err = "DataItem::tableExists() failed - " . $e->getMessage();
912  trace($err, 2);
913  throw new DataItemException($err);
914  }
915 
916  return $exists;
917  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getConnection()
Retrieves a connection to the database.

◆ toJSON()

DataItem::toJSON ( )

Definition at line 1403 of file data_item.inc.

1404  {
1405  $out = array();
1406 
1407  foreach($this->getFields() as $field => $type)
1408  {
1409  if ($this->filter && $this->filter->isExcluded($field))
1410  {
1411  continue;
1412  }
1413 
1414  $val = str_replace("\\'", "'", jsSafe($this->get($field)));
1415 
1416  $out[] = "\"{$field}\": \"".$val."\"";
1417  }
1418 
1419  return "{".implode(", ", $out)."}";
1420  }
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327
jsSafe($str, $escapeEntities=false)
Utility function to escape a string correctly for use in a Javascript client-side call...
Definition: functions.inc:434

◆ toXML()

DataItem::toXML (   $indent = 0,
  $path = null 
)

Generates an XML representation of the object.

Filters are honored when determining which fields are included in the XML. Empty fields are not output (note that a string field with value "" is not considered empty).

Definition at line 1297 of file data_item.inc.

1298  {
1299  trace(get_class($this)."->toXML()", 4);
1300 
1301  $xml = str_repeat(" ", $indent) . "<" . get_class($this) . ">\n";
1302 
1303  foreach($this->getFields() as $field => $type)
1304  {
1305  if ($this->filter && $this->filter->isExcluded($field)) continue;
1306  if (isset($this->$field))
1307  {
1308  if ($this->$field === "")
1309  {
1310  $xml .= str_repeat(" ", $indent) . " <$field/>\n";
1311  }
1312  else
1313  {
1314  $xml .= str_repeat(" ", $indent) . " <{$field}>".$this->formatFieldForXML($field)."</$field>\n";
1315  }
1316 
1317  }
1318  }
1319 
1320  $path[get_class($this)] = true;
1321  trace(implode(" > ", array_keys($path)), 4);
1322  trace("Options: ".$this->_options, 4);
1323 
1324  if (($this->_options & SerializeRelations) ||
1325  ($this->_options & SerializeDirectRelations) &&
1326  $this->relations)
1327  {
1328  if (is_array($this->relations))
1329  {
1330  foreach($this->relations as $rel => $relType)
1331  {
1332  if (is_array($path) && array_key_exists($relType, $path)) continue;
1333 
1334  $obj = $this->$rel();
1335  if ($obj)
1336  {
1337  $xml .= str_repeat(" ", $indent) . " <$rel>\n";
1338 
1339  if (is_array($obj))
1340  {
1341  foreach($obj as $item)
1342  {
1343  if ($this->_options & SerializeRelations)
1344  {
1345  $item->setOption(SerializeRelations);
1346  }
1347 
1348  if ($this->_options & ProtectHTML)
1349  {
1350  $item->setOption(ProtectHTML);
1351  }
1352 
1353  $xml .= $item->toXML($indent + 2, $path);
1354  }
1355  }
1356  else
1357  {
1358  if ($this->_options & SerializeRelations)
1359  {
1360  $obj->setOption(SerializeRelations);
1361  }
1362 
1363  if ($this->_options & ProtectHTML)
1364  {
1365  $obj->setOption(ProtectHTML);
1366  }
1367 
1368  $xml .= $obj->toXML($indent + 2, $path);
1369  }
1370 
1371  $xml .= str_repeat(" ", $indent) . " </$rel>\n";
1372  }
1373  else
1374  {
1375  $xml .= str_repeat(" ", $indent) . " <$rel/>\n";
1376  }
1377  }
1378  }
1379  }
1380 
1381  $xml .= str_repeat(" ", $indent) . "</" . get_class($this) . ">\n";
1382 
1383  return $xml;
1384  }
const SerializeRelations
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327
const SerializeDirectRelations
const ProtectHTML

◆ update()

DataItem::update ( )

Update the row in the database that corresponds to this object.

Definition at line 660 of file data_item.inc.

661  {
662  $pk = $this->primary_key;
663 
664  $query = "UPDATE {$this->table} SET ";
665 
666  $first = true;
667  $found = false;
668 
669  foreach($this->getFields() as $field => $type)
670  {
671  if ($field == $this->primary_key) continue;
672  if ($this->filter && $this->filter->isExcluded($field)) continue;
673  if (!isset($this->$field) && $this->getType($field) != Timestamp && $this->getType($field) != Boolean) continue;
674 
675  if (!$first) $query .= ", ";
676 
677  $first = false;
678  $found = true;
679 
680  $query .= "$field=";
681  $query .= $this->quoteFieldValue($field, $type);
682  }
683 
684  if (!$found) return true; // No fields to update - bug out quietly
685 
686  $query .= " WHERE $pk={$this->$pk} ".$this->getIdentityConstraint();
687 
688  trace("DataItem::update() - $query", 3);
689 
690  try
691  {
692  $db = $this->getConnection();
693 
694  $success = $db->exec($query);
695  if ($success === FALSE)
696  {
697  trace("DataItem::update failed - $query", 2);
698  }
699  else
700  {
701  $this->fireEvent("onUpdate");
702  }
703  }
704  catch(PDOException $e)
705  {
706  $err = "DataItem::update() failed - " . $e->getMessage();
707  trace($err, 2);
708  throw new DataItemException($err);
709  }
710 
711  return $success;
712  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
getFields()
Retrieve the field type list for this object.
Definition: data_item.inc:327
getConnection()
Retrieves a connection to the database.
fireEvent($event)
Fires the specified event to all registered handlers.
Definition: data_item.inc:164
getType($field)
Retrieves the data type of the specified field.
Definition: data_item.inc:490
quoteFieldValue($field, $type)
Returns the properly quoted value of the specified field.

◆ updateExplicit()

DataItem::updateExplicit (   $updates,
  $params = null 
)

Executes an explicit update command against the database.

This enables you to perform updates on the object using database functions, allowing for atomic operations, etc. For example, you might make such a call as $obj->updateExplicit("SET count=count+1"); The object is refreshed from the database automatically after the update.

Parameters
string$updatesthe update command to be run
array$paramsoptional array for bound parameters
Returns
boolean TRUE if the update was successful, FALSE if not.

Definition at line 724 of file data_item.inc.

725  {
726  $pk = $this->primary_key;
727 
728  $query = "UPDATE {$this->table} $updates";
729 
730  if ($this->get($pk))
731  {
732  $query .= " WHERE {$pk}=".$this->get($pk);
733  }
734 
735  trace("DataItem::update() - $query", 3);
736 
737  try
738  {
739  $db = $this->getConnection();
740  $stmt = $db->prepare($query);
741  $success = $stmt->execute($params);
742  if ($success === FALSE)
743  {
744  trace("DataItem::updateExplicit failed - $query", 2);
745  }
746  if ($this->get($pk)) $this->select();
747  }
748  catch(PDOException $e)
749  {
750  $err = "DataItem::updateExplicit() failed - " . $e->getMessage();
751  trace($err, 2);
752  throw new DataItemException($err);
753  }
754 
755  return $success;
756  }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
select()
Select the object from the database, based on the value of the primary key field. ...
Definition: data_item.inc:609
getConnection()
Retrieves a connection to the database.

Member Data Documentation

◆ $_eventMap

DataItem::$_eventMap = array()
static

Definition at line 59 of file data_item.inc.

◆ $_pkDisabled

DataItem::$_pkDisabled = false

Definition at line 62 of file data_item.inc.

◆ $_tx

DataItem::$_tx = null

Definition at line 61 of file data_item.inc.

◆ $dataTypeRendererMap

DataItem::$dataTypeRendererMap
static
Initial value:
= array(
"Boolean" => BooleanTypeRenderer,
"Currency" => CurrencyTypeRenderer,
"Currency3" => CurrencyTypeRenderer,
"Date" => DateTypeRenderer,
"DateTime" => DateTimeTypeRenderer,
"Number" => NumberTypeRenderer,
"String" => StringTypeRenderer,
"Text" => TextTypeRenderer,
"HTML" => TextTypeRenderer,
"Timestamp" => TimestampTypeRenderer,
"Timezone" => TimezoneTypeRenderer,
"PhoneNumber" => PhoneNumberTypeRenderer,
"DateOfBirth" => DateTypeRenderer
)

Definition at line 66 of file data_item.inc.


The documentation for this class was generated from the following file: