Example #1
0
 /**
  * Get paginated row data
  *
  * Returns the Nth "page" of objects, assuming Y objects per page.
  * Defaults to assuming the first page, with 50 objects per page, is
  * desired.
  *
  * @param integer $num The page number to retrieve
  * @param integer $count The number of rows to retrieve
  * @param string $sorts How the results should be sorted
  * @return array
  */
 public static function page($num = 1, $count = 50, $sorts = 'pkeys')
 {
     $class = get_called_class();
     $table = static::table_for_class($class);
     $cols = static::column_names($class);
     $pkeys = static::primary_keys($class);
     $order = array();
     if ($sorts == 'pkeys') {
         $name = "_page_{$table}_pkeys";
         foreach ($pkeys as $pkey) {
             array_push($order, "{$pkey} ASC");
         }
     } else {
         $idx = array();
         foreach ($sorts as $sort) {
             if (preg_match('/^(.*)\\s*(ASC|DESC)$/i', $sort, $matches)) {
                 $sort = $matches[1];
                 $order = strtoupper($matches[2]);
             } else {
                 $order = 'ASC';
             }
             $index = array_search($sort, $cols);
             if ($index === false) {
                 $msg = "{$sort} is not a valid column for sorting";
                 throw new BadColumnException($table, $sort, $msg);
             }
             $sort = Database::quote_identifier($sort);
             array_push($idx, $index . ($order == 'ASC' ? '+' : '-'));
             array_push($order, "{$sort} {$order}");
         }
         $name = "_page_{$table}_" . join($idx, ',');
     }
     $cols = array_values(Database::quote_identifiers($cols));
     $table = Database::quote_identifier($table);
     if (Database::prepared($name)) {
         $query = '';
     } else {
         $cols = join(', ', $cols);
         $ords = join(', ', $order);
         $query = "SELECT {$cols} FROM {$table} ORDER BY {$ords} " . 'LIMIT $1 OFFSET $2';
     }
     $offset = ($num - 1) * $count;
     $return = array();
     $result = Database::prefetch($query, array($count, $offset), $name);
     foreach ($result as $row) {
         $obj = new $class();
         $obj->_set_all($row);
         array_push($return, $obj);
     }
     return $return;
 }