Skip to main content

Zend Framework WebServices

REST Web Services use service-specific XML formats. These ad-hoc standards mean that the manner for accessing a REST web service is different for each service. REST web services typically use URL parameters (GET data) or path information for requesting data and POST data for sending data.

Zend Framework provides both Client and Server capabilities, which, when used together allow for a much more "local" interface experience via virtual object property access. The Server component features automatic exposition of functions and classes using a meaningful and simple XML format. When accessing these services using the Client, it is possible to easily retrieve the return data from the remote call. Should you wish to use the client with a non-Zend_Rest_Server based service, it will still provide easier data access.

In addition to Zend_Rest_Server and Zend_Rest_Client components, Zend_Rest_Route and Zend_Rest_Controller classes are provided to aid routing REST requests to controllers.


1. Zend_Rest

1.1 Introduction

Using the Zend_Rest_Client is very similar to using SoapClient objects (SOAP web service extension). You can simply call the REST service procedures as Zend_Rest_Client methods. Specify the service's full address in the Zend_Rest_Client constructor.

Example 1.1. A basic REST request

sayHello('Davey', 'Day')->get(); // "Hello Davey, Good Day"
[Note] Differences in calling

Zend_Rest_Client attempts to make remote methods look as much like native methods as possible, the only difference being that you must follow the method call with one of either get(), post(), put() or delete(). This call may be made via method chaining or in separate method calls:

sayHello('Davey', 'Day');
echo $client->get();

1.2.1 Responses

All requests made using Zend_Rest_Client return a Zend_Rest_Client_Response object. This object has many properties that make it easier to access the results.

When the service is based on Zend_Rest_Server, Zend_Rest_Client can make several assumptions about the response, including response status (success or failure) and return type.

Example 1.2. Response Status

sayHello('Davey', 'Day')->get();

if ($result->isSuccess()) {
echo $result; // "Hello Davey, Good Day"
}

In the example above, you can see that we use the request result as an object, to call isSuccess(), and then because of __toString(), we can simply echo the object to get the result. Zend_Rest_Client_Response will allow you to echo any scalar value. For complex types, you can use either array or object notation.

If however, you wish to query a service not using Zend_Rest_Server the Zend_Rest_Client_Response object will behave more like a SimpleXMLElement. However, to make things easier, it will automatically query the XML using XPath if the property is not a direct descendant of the document root element. Additionally, if you access a property as a method, you will receive the PHP value for the object, or an array of PHP value results.

Example 1.3. Using Technorati's Rest Service

key($key);
$technorati->url('http://pixelated-dreams.com');
$result = $technorati->get();
echo $result->firstname() .' '. $result->lastname();

Example 1.4. Example Technorati Response




<?xml version="1.0" encoding="utf-8"?>
<!-- generator="Technorati API version 1.0 /bloginfo" -->
<!DOCTYPE tapi PUBLIC "-//Technorati, Inc.//DTD TAPI 0.02//EN" "http://api.technorati.com/dtd/tapi-002.xml">
<tapi version="1.0">
<document>
<result>
<url>http://pixelated-dreams.com</url>

<weblog>
<name>Pixelated Dreams</name>
<url>http://pixelated-dreams.com</url>
<author>
<username>DShafik</username>

<firstname>Davey</firstname>
<lastname>Shafik</lastname>
</author>
<rssurl>http://pixelated-dreams.com/feeds/index.rss2</rssurl>

<atomurl>http://pixelated-dreams.com/feeds/atom.xml</atomurl>
<inboundblogs>44</inboundblogs>
<inboundlinks>218</inboundlinks>
<lastupdate>2006-04-26 04:36:36 GMT</lastupdate>

<rank>60635</rank>
</weblog>
<inboundblogs>44</inboundblogs>
<inboundlinks>218</inboundlinks>

</result>
</document>
</tapi>

Here we are accessing the firstname and lastname properties. Even though these are not top-level elements, they are automatically returned when accessed by name.

[Note] Multiple items

If multiple items are found when accessing a value by name, an array of SimpleXMLElements will be returned; accessing via method notation will return an array of PHP values.

1.2.3 Request Arguments

Unless you are making a request to a Zend_Rest_Server based service, chances are you will need to send multiple arguments with your request. This is done by calling a method with the name of the argument, passing in the value as the first (and only) argument. Each of these method calls returns the object itself, allowing for chaining, or "fluent" usage. The first call, or the first argument if you pass in more than one argument, is always assumed to be the method when calling a Zend_Rest_Server service.

Example 1.2.4. Setting Request Arguments

arg('value1');
$client->arg2('value2');
$client->get();

// or

$client->arg('value1')->arg2('value2')->get();

Both of the methods in the example above, will result in the following get args: ?method=arg&arg1=value1&arg=value1&arg2=value2

You will notice that the first call of $client->arg('value1'); resulted in both method=arg&arg1=value1 and arg=value1; this is so that Zend_Rest_Server can understand the request properly, rather than requiring pre-existing knowledge of the service.

[Warning] Strictness of Zend_Rest_Client

Any REST service that is strict about the arguments it receives will likely fail using Zend_Rest_Client, because of the behavior described above. This is not a common practice and should not cause problems.




2.1. Zend_Rest_Server

2.1.1. Introduction

Zend_Rest_Server is intended as a fully-featured REST server.

2.2.2. REST Server Usage

Example 2.2.1. Basic Zend_Rest_Server Usage - Classes

setClass('My_Service_Class');
$server->handle();

Example 2.2.3. Basic Zend_Rest_Server Usage - Functions

addFunction('sayHello');
$server->handle();

2.3. Calling a Zend_Rest_Server Service

To call a Zend_Rest_Server service, you must supply a GET/POST method argument with a value that is the method you wish to call. You can then follow that up with any number of arguments using either the name of the argument (i.e. "who") or using arg following by the numeric position of the argument (i.e. "arg1").

[Note] Numeric index

Numeric arguments use a 1-based index.

To call sayHello from the example above, you can use either:

?method=sayHello&who=Davey&when=Day

or:

?method=sayHello&arg1=Davey&arg2=Day

2.3.1. Sending A Custom Status

When returning values, to return a custom status, you may return an array with a status key.

Example 2.3.1.1. Returning Custom Status

 "An Error Occurred", 'status' => false);
}

$server = new Zend_Rest_Server();
$server->addFunction('sayHello');
$server->handle();

2.3.2. Returning Custom XML Responses

If you wish to return custom XML, simply return a DOMDocument, DOMElement or SimpleXMLElement object.

Example 2.3.2.1 Return Custom XML



Hey $who! Hope you're having a good $when
200
';

$xml = simplexml_load_string($xml);
return $xml;
}

$server = new Zend_Rest_Server();
$server->addFunction('sayHello');

$server->handle();

The response from the service will be returned without modification to the client.


Comments

Popular posts from this blog

Optimizing PHP

The more you understand the software you are using (Apache, PHP, IIS, your database) and the deeper your knowledge of the operating system, networking and server hardware, the better you can perform global optimizations on your code and your system. Try to use as much caching as possible, typically I would use this configuration: Squid -- PHP and memcache or file caching -- Database. For PHP scripts, the most expensive bottleneck is normally the CPU. If you are not getting out of memory messages, more CPUs are probably more useful than more RAM. Compile PHP with the "configure –-enable-inline-optimization" option to generate the fastest possible PHP executable. Tune your database and index the fields that are commonly used in your SQL WHERE criteria.  ADOdb , the very popular database abstraction library, provides a  SQL tuning mode , where you can view your invalid, expensive and suspicious SQL, their execution plans and in which PHP script the SQL was executed. Use...

Node.js best practices you should follow

Node.js is a platform built on Chrome’s JavaScript engine (i.e. v8 JavaScript Engine); it helps to develop fast, scalable network application. It is basically used in server side coding, handling AJAX requests, maintaining routes for different APIs and manipulating database. Node.js uses an event-driven, non blocking I/O model that makes it lightweight and efficient. Now without defining v8 the blog will remain incomplete.  v8  is Google’s open source JavaScript engine which is written in C++. Best feature of v8 is: it can run independently, or can be embedded into any C++ application. Let’s come to the main topic; here are the Node.js best practices: 1. Learn the best practices of JavaScript first: Before starting Node.js you should learn the best practices of JavaScript first. It will make your code more decent and flexible. There is a statement code lovers always use, “A fool can write codes which only machines can understand”. So, my suggestion is follo...

JavaScript coding standards we follow

This document’s primary motivation is twofold: 1) code consistency 2) best practices. By  maintaining consistency in coding styles and conventions, we can ease the burden of legacy code maintenance, and mitigate risk of breakage in the future. By adhering to best practices, we ensure optimized page loading, performance and maintainable code. Therefore, at Innofied, we follow these guidelines strictly while programming. 1 . Proper File Naming Conventions a) Use Constructor function name as file names. So as per example, file name will be Hero.js For example: 1 2 3 function Hero ( ) {    this . occupation = ‘ Ninja ’ ; } b) Choose meaningful file names for your JavaScript files like the file names should be derived or chosen by focusing on what the file holds and use CamelCase for your file names. 2 . Indentation a) The unit of indentation is 4 spaces. b) Use of tabs should be avoided. c) Use “format” ...