Web services in CakePHP February 16, 2006
Posted by rossoft in CakePHP.trackback
I can’t wait to 1.0 for having web services and I started a simple soap component.
Installation
1. Copy this file to /app/controllers/components
2. Download nusoap library and put the file nusoap.php on /vendors/nusoap
3. Replace all the ocurrences of “soapclient” to “soap_client” on that file. This is for compatibility with PHP5, it has another soapclient class.
Usage
Developing a server
The service will be in the url http://myhost/test/get_info
(open that url in your browser for see the info of the webservice)
1. The controller
class TestController extends AppController
{
var $components=array(‘aaa’,'bbb’,’soap’);
function get_info()
{
$this->soap->service();
}
}
2. The service.
With this line $this->soap->service() we’re telling the soap component to register the service at the file /app/controllers/soap_services/test/get_info.php , so we need to create that file:
global $api;
$api=array( ‘doc’=>’Returns the price of the article’,
‘input’=> array(‘code’=>’xsd:string’),
‘output’=> array(‘return’=>’xsd:float’));
function get_info($code)
{
global $controller;
$data=$controller->Article->findAll(array(“‘Article.code’='$code”));
return $data[0]['Article']['price'];
}
?>
That’s all. The method can access the Test controller through the controller global variable. Then it can call a method of the model.
Important: the $api variable must be declared. It has a description of the method (‘doc’), the array of input values (‘input’) and the array of output values (‘output’).
Developing a client
class Test2Controller extends AppController
{
var $components=array(‘aaa’,'bbb’,’soap’);
function price()
{
$url=”http://localhost/test/get_info”;
$func=’get_info’;
$param=array(‘code’=>’W03921′);
$price=$this->soap->client($url,$func,$param);
$this->set(‘price’,$price);
}
}
Then, create the view for this action and put on it
[...] At the moment, CakePHP does not have built-in support for webservices (but it is planned for version 1.0). Miguel Ros could not wait until that feature is available, so he experimented a little bit. He presents two approaches using the NuSOAP toolkit in his blog (approach 1, approach 2). I prefer the second approach as it looks more cake-like. [...]
If you are getting no response or an empty response from the server when using the client you may want to add ‘wsdl’ as a second parameter to the client instanciation like so:
$client = new soap_client($url, ‘wsdl’);
Also, if you want to be able to check for errors from the controller, use a class variable to assign the client(or server) to:
$this->client = new soap_client($url, ‘wsdl’);
You will then be able to get at the errors in your controller like so:
$this->soap->client->getError();
very bad design. global $api. BAH! bad. really bad!