Sunday, November 22, 2009

RESTful PHP Applications Despite Zend Framework

At the moment there’s a couple of blog posts doing the rounds explaining and promoting the new REST components in Zend Framework.

Here’s the problem:

Why do I say that?

REST isn't just collection/item CRUD over HTTP, and it's not about URI templating. Frameworks that don’t agree with this are needlessly restricting and/or confusing developers; when the only (debatable) ‘benefit’ of the approach is that collection and item resources can be handled by one controller and one route.

It bothers me so much I made an extension for Zend Framework that approaches things a bit better – it’s called Resauce:

Resauce is a small extension to Zend Framework. It gives you a lightweight framework for building RESTful HTTP interfaces with PHP.

The main idea is to treat each controller as a Resource; i.e. a controller is responsible for one resource. This is distinct from other solutions (such as the REST components included in ZF itself) where a controller is responsible for both collection and item resources.

Example routes in a Resauce application:

‘/blog’ >> BlogController
‘/blog/:post’ >> BlogPostController
‘/blog/:post/comments’ >> BlogPostCommentsController

A route in a Resauce application simply maps a URI pattern to a Resauce controller – no controller action should ever be specified in a route. Instead – controller actions are ‘routed’ according to the HTTP method of a given request:

GET >> getAction()
PUT >> putAction()
POST >> postAction()
DELETE >> deleteAction()
HEAD >> headAction()
OPTIONS >> optionsAction()

If a request is routed to a Resauce controller which does not have an action implemented for the given HTTP method, then the Resauce will automatically respond with a 405 Method Not Allowed response code.

.. More on github

The Resauce approach to MVC provides much more flexibility over how resources can be exposed than other alternatives – you have complete control of URI patterns and each resource’s HTTP methods

Check it out, and let me know what you think :)