RSS

Creating web services using PHP

08 Jun

First of all I want to explain or define what is web service ? You can think of web services as DLL files over the web you write the code then compile it and every one can use it whatever the language they are using , but in the web you don’t compile anything . Actually when I started using webservices , I was writing c# code so .Net was doing every thing for me. I couldn’t understand what is happening behind the scene I just type [webservice] above the function and everything is running. So In this article i ‘m going to explain what is happening.

How it works?

1) WSDL

First you have to define what you are serving. Think of it as a menu in a restaurant. You can define this by creating WSDL file (web service definition language). You actually define what are the functions you are using.

2) SOAP

You can consider SOAP as a waiter in a restaurant. He writes your order, delivers it to the kitchen and gets the food back to you, that is actually what the soap does; you encapsulate your request to a standard format that matches the definitions in your WSDL file. And the server in the return encapsulates the result into a standard format based also on the WSDL file; you can consider the WSDL file as the menu in the restaurant. You have to order something from the menu, and the kitchen has to deliver to you what you requested according to the details on the menu.

What do you need?

php soap

If you are using php 5 or more  on windows, go to your php.ini and uncomment the following line extension=php_soap.dll. When run your phpinfo you should see it installed.

If you are using linux, you can install it using the following line:

yum install php-soap

if you are using php 4 you can use nusoap

Creating your first web service

we are going to create a web service for a library , users can search for authors, books , browse each author’s books

Each author has the following :

author_id

author_name

And each book has the following:

book_id

book_name

author_id

We are going to assume that each book is written by only one author to simplify the example

Creating the WSDL file

I’m going now to create the WSDL file “menu”. Here is the code:

<?xml version="1.0" encoding="UTF-8"?>

<wsdl:definitions name="Library" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="Library" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="Library" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"  >

    <xsd:documentation></xsd:documentation>
    <wsdl:types>
     <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="Library">
            <xsd:complexType name="Book">

                <xsd:sequence>
                 <xsd:element name="ID" type="xsd:integer"></xsd:element>
                 <xsd:element name="NAME" type="xsd:string" ></xsd:element>

                 <xsd:element name="AUTHOR" type="tns:Author" ></xsd:element>
                </xsd:sequence>
            </xsd:complexType>

            <xsd:complexType name="Author">

                <xsd:sequence>
                 <xsd:element name="ID" type="xsd:integer"></xsd:element>
                 <xsd:element name="NAME" type="xsd:string" ></xsd:element>

              <xsd:element name="BOOKS" type="tns:Book"
               minOccurs="0" maxOccurs="unbounded">
              </xsd:element>

             </xsd:sequence>
            </xsd:complexType>

            <xsd:complexType name="Authors">
                <xsd:sequence>
              <xsd:element name="AUTHOR" type="tns:Author"

               minOccurs="0" maxOccurs="unbounded">
              </xsd:element>
             </xsd:sequence>
            </xsd:complexType>

            <xsd:complexType name="Books">
                <xsd:sequence>
              <xsd:element name="BOOK" type="tns:Book"
               minOccurs="0" maxOccurs="unbounded">

              </xsd:element>
             </xsd:sequence>
            </xsd:complexType>
     </xsd:schema></wsdl:types>
  <wsdl:message name="searchAuthorsRequest">

   <wsdl:part name="NAME" type="xsd:string"></wsdl:part>
  </wsdl:message>
  <wsdl:message name="searchAuthorsResponse">
   <wsdl:part name="AUTHORS" type="tns:Authors"></wsdl:part>

  </wsdl:message>
  <wsdl:message name="searchBooksRequest">
   <wsdl:part name="NAME" type="xsd:string"></wsdl:part>
  </wsdl:message>

  <wsdl:message name="searchBooksResponse">
   <wsdl:part name="BOOKS" type="tns:Books"></wsdl:part>
  </wsdl:message>
  <wsdl:portType name="Library">

    <wsdl:operation name="searchAuthors">
      <wsdl:input message="tns:searchAuthorsRequest"/>
      <wsdl:output message="tns:searchAuthorsResponse"/>
    </wsdl:operation>

    <wsdl:operation name="searchBooks">
     <wsdl:input message="tns:searchBooksRequest"></wsdl:input>
     <wsdl:output message="tns:searchBooksResponse"></wsdl:output>
    </wsdl:operation>

 </wsdl:portType>
  <wsdl:binding name="Library" type="tns:Library">
   <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />

   <wsdl:operation name="searchAuthors">
    <soap:operation soapAction="http://localhost/Blog/Library/library.php" />
    <wsdl:input>
     <soap:body use="literal" namespace="Library" />

    </wsdl:input>

    <wsdl:output>
     <soap:body use="literal" namespace="Library" />
    </wsdl:output>

   </wsdl:operation>

   <wsdl:operation name="searchBooks">
    <soap:operation soapAction="http://localhost/Blog/Library/library.php" />
    <wsdl:input>

     <soap:body use="literal" namespace="Library" />
    </wsdl:input>
    <wsdl:output>
     <soap:body use="literal" namespace="Library" />

    </wsdl:output>
   </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="Library">
    <wsdl:port binding="tns:Library" name="YLibrary">

      <soap:address location="http://localhost/Blog/Library/library.php" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

the wsdl file contains main 4 parts :

  1. types
    You simply define the types that you are going to use , it looks like the variables definition in a PASCAL program.
  2. messages
    Each function in the web service has two messages; one for the input and the other for the output , also you can add one message to handle the exception.
  3. port type
    the port type combines one or more messages to represent a function. For example the “searchBooks” operation combines two messages; one for the input and one for the response.
  4. binding
    In the binding section , you define protocol details for the web service

I will create two classes to hold the data  one for books and the other for authors. Please notice that you have to name the members exactly the same way you did in the WSDL file.

The BookData class

<?php
class BookData {
     public $ID; 
     public $NAME; 
     public $AUTHOR; 
}
?>

The Author Data class

<?php
class AuthorData {
 public $ID; 
 public $NAME;
 public $BOOKS; 
}
?>

now I am going to create wrapper classes

Book class

<?php
class Book {
 private $_nID; 
 private $_strName; 

 public function __construct($ID,$Name){
  $this->SetID($ID); 
  $this->SetName($Name); 
 }
 public function SetID($ID){
  $this->_nID=mysql_real_escape_string($ID); 
 }

 public function GetID(){
  return $this->_nID; 
 }

 public function SetName($Name){
  $this->_strName=mysql_real_escape_string($Name); 
 }

 public function GetName () {
  return $this->_strName; 
 }

 public function CreateBook (){
  //Code to create Book
 }

 public function UpdateBook () {
  //code to update book 
 }

 public function DeleteBook () {
  //code to delete book 
 }
 public function SearchBooks () {
  $SQL = "SELECT * FROM books 
          INNER JOIN authors on books.author_id= authors.author_id
          WHERE books.book_name like '%{$this->_strName}%'";
  $Query = mysql_query($SQL) or die (mysql_error()); 
  $NumOfBooks = mysql_num_rows($Query); 
  $Result= array () ; 
  for ($i=0;$iID=mysql_result($Query, $i,"author_id");
    $Author->NAME=mysql_result($Query, $i,"author_name");
    //we will set this when we search by author name
    $Author->BOOKS=array(); 
    $Book = new BookData(); 
    $Book->ID = mysql_result($Query, $i,"book_id"); 
    $Book->NAME=mysql_result($Query, $i,"book_name");
    $Book->AUTHOR=$Author;

    $Result[]= $Book; 
  }
  return $Result; 
 }
}
?>

Author Class

<?php
class Author {

 private $_nID; 
 private $_strName; 

 public function __construct($ID,$Name){
  $this->SetID($ID); 
  $this->SetName($Name); 
 }

 public function SetID($ID){
  $this->_nID=mysql_real_escape_string($ID); 
 }

 public function GetID(){
  return $this->_nID; 
 }

 public function SetName($Name){
  $this->_strName=mysql_real_escape_string($Name); 
 }

 public function GetName () {
  return $this->_strName; 
 }

 public function CreateAuthor (){
  //Code to create Author
 }

 public function UpdateAuthor() {
  //code to update Author
 }

 public function DeleteAuthpr() {
  //code to delete Author
 }

 public function SearchAuthors() {
  $SQL = "SELECT * FROM authors WHERE authors.author_name like '%{$this->_strName}%'"; 
  $Query = mysql_query($SQL) or die (mysql_error()); 
  $NumOfAuthors= mysql_num_rows($Query); 

  $Result= array () ; 

  for ($i=0;$iID=mysql_result($Query, $i,"author_id");
                                $Author->NAME=mysql_result($Query, $i,"author_name");
    $Author->BOOKS=$this->GetBooksByAuthorID($Author->ID);  
    $Result[]= $Author; 
  }
  return $Result; 
 }

 public function GetBooksByAuthorID($ID){

  $SQL = "SELECT * FROM books WHERE author_id = $ID"; 

  $Query = mysql_query($SQL);  
  $NumOfBooks = mysql_num_rows($Query); 

  $Result = array () ; 

  for($i=0;$iID=mysql_result($Query, $i,"books.book_id");
    $Book->NAME=mysql_result($Query, $i,"books.book_name");

   $Result[]= $Book ; 

  }
  return $Result; 
 }
}
?>

Finally we will create php file who is supposed to receive the request from soap clients and return results. This file is the one written in the soap action attribute in the WSDL file.

library.php

<?php

mysql_connect("localhost","root",""); 
mysql_select_db("library");

function __autoload($ClassName) {
 require_once $ClassName.".php";
}

function searchAuthors ($NAME) {
 $Author = new Author(null, $NAME); 
 return $Author->SearchAuthors();
}

function searchBooks($NAME){
 $Book = new Book(null, $NAME); 
 return $Book->searchBooks();
}

ini_set("soap.wsdl_cache_enabled", "0"); 

$classmap = array(
 "Book"=>"BookData",
 "Author"=>"AuthorData"
);
$server = new SoapServer("Library.wsdl",array("classmap"=>$classmap));
$server->addFunction("searchAuthors"); 
$server->addFunction("searchBooks"); 
$server->handle();
?>

Please notice you have to create a map between your complex types and your classes “the ones that hold the data”.

For example here, I mapped between Book “the complex type in the WSDL file” and BookData “The php class”.

Now everything is ready. Lets call the web service:

index.php

<?php
$client = new SoapClient("http://localhost/Blog/Library/Library.wsdl",array("trace" => 1)); 
try
{
 $response = $client->searchAuthors("Beh");
 //$response = $client->searchBooks("comp");

 var_dump($response);
 echo "Request".htmlspecialchars($client->__getLastRequest())."";
 echo "Response".htmlspecialchars($client->__getLastResponse())."";

}catch(Exception $e){
 var_dump($e);
 echo $client->__getLastRequest();
 echo $client->__getLastResponse();
}
?>
Advertisements
 
Leave a comment

Posted by on June 8, 2011 in Mixed, PHP

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: