Building a collection resource

In a RESTful application there are two types of resources, regular resources that contain our applications data, and collection resources that contain other resources. A collection resource usually has the ability to list its contents and add new resources to itself.

For example, say we want to model a list of cookery recipies, first we define our recipe resource class:

class Recipe extends Resource {
	var $name;
	var $serves;
	var $ingredients;
	var $method;
}
lib/recipe.php

Lets say we create resources at /recipes/[recipe name], we probably want to create a list of them at /recipes so that our clients can find them. Except we're not really "creating a list", we're creating a representation of our collection resource.

So first, lets create said collection resource:

class RecipeCollection extends SmartyResource {
	
	function get($request) {
		$this->_smarty->assign_by_ref('recipies', Resource::findAll($this->_adapter, $this->url));
		return parent::get($request);
	}
	
}
lib/recipeCollection.php

The get method of collection resource grabs all of the resources that start with the resources own URL, thus all sub-resources, all our recipes.

Finally all we need is a representation for our collection:

<?xml version="1.0"?>
<recipes>
{foreach from=$recipes item=recipe}
	<recipe href="/repipes/{$recipe->name|escape:"url"}">{$recipe->name|escape}</recipe>
{/foreach}
</recipes>
resource/recipes/default.xml Back to documentation home
Created Feb 17, 2008, last modified Feb 17, 2008