I will compose another post to describe my comparison about SOAP WS and RESTful WS and JSON-RPC. Here, I will show a simple demo about how to create Zend_Rest_Server based RESTful WS in Zend Studio. Zend_Rest_Server is not perfect. For instances, it can not work together with Zend_Action_Router_Route. It also asked for calling function by put "method=functionName" in requesting URL after the "?". This make some guys think it is not RESTful WS as some person said it is not good design. But, I think it is not wrong design at least. Below is source for simple ZF based RESTful WS.
- Create a new ZF project in Zend Studio and name it as jiaRESTfulWS.
- Add autoloaderNamespaces[] = "Jia_" in application.ini to allow Zend Autoloader load Jia_* classes.
- Creating a action class DummyController under directory /application/controllers.
- creating a function restAction() in DummyController .
- Creating a Jia_Hello class with sayHello($name) function under /library/Jia directory.
Jia_Hello class
/**
* This class contains function which will be used by Web service caller.
* All business logics will be implented or called in these functions.
*
* @author Yiyu Jia
*
*/
class Jia_Hello {
/**
*
* @param string $name
* @return string
*
*/
public function sayHello($name){
return "hello ".$name;
}
}
DummyController class
/**
* This class includes one function restAction(), wich has Zend_Rest_Server initialized.
* However, you can only use URI with "?" like this "/rest?method=sayHello&name=jia". You
* can not have URI like "/rest/name/jia"
*
* @author yiyu
*
*/
class DummyController extends Zend_Controller_Action
{
/**
* action named as rest.
*/
public function restAction() {
// disable layouts and renderers
$this->getHelper ( 'viewRenderer' )->setNoRender ( true );
// initialize REST server
$server = new Zend_Rest_Server();
// set REST service class
$server->setClass ( 'Jia_Hello' );
// handle request
$server->handle ();
}
}
Zend Studio 7.2 project file can be downloaded here. Also, I do not recommend to use Zend_Rest_Server for developing RESTful WS as I think it is old and uncompleted class. Zend_Rest_Route should be a better choice to make RESTful Web Service in PHP. Here is a simple tutorial about how to use Zend_Rest_Route and Zend_Rest_Controller to create RESTful Web Service. Creating RESTful service with Zend_Rest_Route and Zend_Rest_Controller