Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Created January 17, 2011 17:44
Show Gist options
  • Save wilmoore/783143 to your computer and use it in GitHub Desktop.
Save wilmoore/783143 to your computer and use it in GitHub Desktop.
Using Traits instead of inheritance to build a Restful Dispatcher in ZF2 MVC
// REF: http://framework.zend.com/wiki/display/ZFDEV2/Proposal+for+MVC+Interfaces
trait RestDispatcher
{
public function dispatch(Request $request, Response $response = null)
{
if (!$request instanceof HttpRequest) {
throw new DomainException('REST expects HTTP requests');
}
$resource = $this->getResource();
switch (strtoupper($request->getMethod())) {
case 'GET':
// ...
break;
case 'POST':
// ...
break;
case 'PUT':
// ...
break;
case 'DELETE':
// ...
break;
case 'HEAD':
// ...
break;
default:
$response->getStatus()->setStatusCode(405, 'Method Not Allowed');
}
return $response;
}
}
// In a controller file:
namespace Blog\Controller;
class Entry implements Dispatchable
{
use RestDispatcher;
public function getResource()
{
return new Blog\Model\EntryResource;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment