Creating a Data Feed

A data feed allows you to combine multiple model classes into a single data collection. This is very useful for creating feeds and streams of data while also supporting the use of pagination. It works by adding model objects in a prepared state, before the find() or find_all() methods are called, which are then combined to make a collection that behaves as a single model. The Db_DataFeed class mimics the Db_ActiveRecord class and supports limit() and paginate().

A simple example of creating a feed is below:

$feed = Db_DataFeed::create();
$feed->add(User::create());
$feed->add(Blog_Comment::create());
$feed->add(Blog_Post::create()->where('category_id=7'));
$feed_items = $feed->limit(10)->find_all();

This example will combine users, blog posts and blog comments in to a single collection that only contains the first 10 results. By default the feed is ordered by the updated_at and created_at fields.

Processing Results

The find_all() method will return a Db_DataCollection object that contains the collection of objects. You can then loop these results and identify it's origin by accessing the class_name property. For example:

foreach ($feed_items as $item)
{
	if ($item->class_name == 'Blog_Post')
		echo "New Blog Post: ".$item->title;
	else if ($item->class_name == 'Blog_Comment')
		echo "New Blog Post Comment: ".$item->content;
	else if ($item->class_name == 'User')
		echo "New User: ".$item->full_name;	
}

Tagging Results

In some cases you may wish to use the same model with a different SQL filter whilst retaining the ability to identify the difference when processing the results. This can be achieved by passing a unique tag name as the second parameter of the add() method. The resulting tag name is then available as the context_name property. For example:

$feed = Db_DataFeed::create();
$feed->add(Blog_Post::create()->where('category_id=2'), 'category_two');
$feed->add(Blog_Post::create()->where('category_id=3'), 'category_three');

foreach ($feed->find_all() as $item)
{
	if ($item->context_name == 'category_two')
		echo "Category 2 Blog Post: ".$item->title;
	else if ($item->context_name == 'category_three')
		echo "Category 3 Blog Post: ".$item->title;
}