In the previous segment, I defined an initial abstraction class that permitted us, among other things, to handle connections to MySQL and perform specified SQL queries through a friendly API. Naturally, the most important method to look at here is “runQuery().” It returns an instance of a class called “MySQLi_ResultWrapper,” whose definition certainly hasn’t been showed so far. Thus, it’s time to reveal the secret and show the initial source code of this class, which will be an implementer of the aforementioned Iterator, Countable and ArrayAccess native interfaces respectively. But I’m getting ahead of myself; for the moment, this class will look like this: class MySQLi_ResultWrapper extends MySQLi_Result { private $_pointer = 0;
// fetch row as an object public function fetchObject() { if (!$row = $this->fetch_object()) { return NULL; } return $row; }
// fetch row as an associative array public function fetchAssocArray() { if (!$row = $this->fetch_assoc()) { return NULL; } return $row; }
// fetch row as an enumerated array public function fetchNumArray() { if (!$row = $this->fetch_row()) { return NULL; } return $row; }
// fetch all rows public function fetchAll($type = MYSQLI_ASSOC) { if ($type !== MYSQLI_ASSOC AND $type !== MYSQLI_NUM AND $type !== MYSQLI_BOTH) { $type = MYSQLI_ASSOC; } if (!$rows = $this->fetch_all($type)) { return NULL; } return $rows; }
// get definition information on fields public function fetchFieldsInfo() { if (!$fieldsInfo = $this->fetch_fields()) { throw new Exception('No information available for table fields.'); } return $fieldsInfo; }
// get definition information on next field public function fetchFieldInfo() { if (!$fieldInfo = $this->fetch_field()) { throw new Exception('No information available for current table field.'); } return $fieldInfo; }
// free up result set public function __destruct() { $this->close(); } } From the above code sample, it’s clear to see that the “MySQLi_ResultWrapper” class is exactly that: a wrapper for the native PHP 5 MySQLi_Result class. In consonance with this, the class implements some proxy methods that allow it to fetch database rows as plain objects, as well as in the form of numerically-indexed and associative arrays. Besides, there are a couple of additional methods that can be used for retrieving information about the fields of a selected table, these don’t bear any further discussion. At this point, the definition of the “MySQLi_ResultWrapper” class is quite easy to follow, but it doesn’t implement any of the interfaces mentioned before. Well, as the old proverb says, a long walk begins with a single step, so it’s time to refactor the class a little bit to make an implementer of the Iterator interface. This process will permit us to iterate over database result sets via a simple “foreach” construct. This topic will be discussed in detail in the section to come. Therefore, to get there, click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|