Using Zend Framework to create a RESTful service

May 7th 2012

Recently, the question came up from a customer of mine about the best way to implement a RESTful service for their mobile applications to speak to.

If this was a couple of years ago, I'd suggest a custom solution, but recently I started using Zend Framework for this exact purpose.

Why use ZendFramwork? Well, the answer is easy. All the work's been done for you. Within a couple of minutes you can have a live RESTful service.

Step one, creating the Bootstrap.

PHP Code:
<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    protected function 
_initRestRoute()
    {
        
$this->bootstrap('frontController');
        
$fc Zend_Controller_Front::getInstance();
        
$route = new Zend_Rest_Route($fc);
        
$fc->getRouter()->addRoute('default'$route);

    }

}

All that does is tell the Framework that it needs to listen for us using the Rest interface.

Step two, add your controller:

PHP Code:
<?php
class InteractionController extends Zend_Rest_Controller {

    public function 
init() {
        
// We don't want to use a view on this controller
        
$this->_helper->viewRenderer->setNoRender true );
    }

    public function 
indexAction() {
        
// The only time you'd see this is if didn't pass a variable in GET
    
}

    public function 
getAction() {
        
// GET COMMAND
    
}

    public function 
postAction() {
        
// POST COMMAND
    
}

    public function 
putAction() {
        
// PUT COMMAND
    
}

    public function 
deleteAction() {
        
// DELETE command
    
}

}

And that's it. If you were to send commands to the controller (yourdomain.com/interaction) then you'd get the response from the relevant action.

Did this help you out?