5.4. Sets and Collections

The Xyster_Data package comes supplied with some objects for working with sets of data.

5.4.1. Xyster_Data_Set

The data set is an editable record set. More specifically, It's a sortable set that can contain only objects and arrays. It can have values fetched from it or items filtered out. For the following examples, let's declare the following class and objects:

<?php

class hero
{
      public $name;
      public $gender;
      public $universe; 

      public function __construct( $name, $gender, $universe )
      {

            $this->name = $name;
            $this->gender = $gender;
            $this->universe = $universe;
      }
}

$punisher = new hero( 'Frank Castle', 'M', 'Marvel' );
$supes = new hero('Clark Kent', 'M', 'DC');
$blackcat = new hero('Felicia Hardy', 'F', 'Marvel');
$catwoman = new hero('Selina Kyle', 'F', 'DC' );

A data set can be constructed from a traversable value containing arrays or objects:

<?php
$heroes = new Xyster_Data_Set();
foreach( array( $punisher, $supes, $blackcat, $catwoman ) as $hero ) {
        $heroes->add($hero);
}

The $set data set would contain the Fields "name", "gender", and "universe". You can also construct a blank set and add Fields to it.

<?php
$heroes = new Xyster_Data_Set();

$heroes->addColumn("name");
$heroes->addColumn("gender");
$heroes->addColumn("universe");

The values in the set can be sorted with the sortBy method which takes one or more Xyster_Data_Sort objects as a parameter.

Note that you can mix arrays and objects in the same sortable set, and for that matter, they can have different columns. However, trying to sort on a column that not every item has will throw an exception.

Data sets can have values fetched or aggregated from them:

<?php
$multiverse = $heroes->fetchColumn('universe');
// $multiverse contains 'Marvel', 'DC', 'Marvel', 'DC'
$name = $heroes->fetchScalar();
// $name contains the first column of the first item
$nameAndGender = $heroes->fetchPairs('name', 'gender');
// $name contains array("Clark Kent"=>"M","Felicia Hardy"=>"F", ..etc.)
$max = $heroes->aggregate(Xyster_Data_Aggregate::Maximum(), 'name');
// $max contains 'Selina Kyle'

They can also be filtered with the filter method.

<?php
$criteria = Xyster_Data_Expression::neq('universe','DC');
$heroes->filter($criteria);
// $heroes would contain 'Felicia Hardy' and 'Frank Castle'

5.4.2. Xyster_Data_Tuple

A tuple is a grouping of records by some common feature. Usually, records are grouped by the same value in one or more columns. For instance, using the objects above, one could create a tuple containing 'Clark Kent' and 'Selina Kyle' because they both have 'DC' in the universe column. Xyster_Data_Tuple has a static method that accepts a number of arguments to make tuples out of a traversable group of values (makeTuples). See the Tuple API documentation for more information.