How to Use PHP for Developing a Web Service?
To begin with, we would like to clear the air about the concept of web services. Irrespective of all that has been said and done in this regard, in the simplest form, a web service remains to be a combination of DLL files which are compiled and uploaded over the internet, and can be accessed by the users in general, regardless of the language that their system is using.
While working on a C# code, all we have to do is to simply type [webservice] and .Net would do the rest of the work for us. However, in this article, we have much more focused approach, and shall factor in PHP development services, simultaneously trying to unravel and understand and appreciate the actual functioning of the backend development. Stay with us, if you would like to understand how web services can be created using PHP.
How does the web service actually works?
There are two concepts in particular that we need to be familiar with, in order to understand the procedure. These two concepts are:
1 – WSDL – WSDL or the Web Service Definition Language enables the developers to express what the web service is going to serve to the users. In this, the developers actually get to define all the functions that they are going to use in the development process.
2 – SOAP – Let us try and learn this concept with the help of an example of an eating joint. Now, you go to an eating joint and browses through the list from the items present in the menu. You let your order be known to the waiter. It is then the responsibility of the waiter to take your order to the culinary department and bring the order back to you on your desks. Where WSDL was the menu – containing the list of all the functions possible, SOAP is our ardent hard working Waiter. It takes the requests of the users via various input methods, matches it with the specifications available, and reverts with the required set of functions.
What all do you require?
To come up with a thorough web service, you would need to have certain things right in place, the list of which includes PHP Soap. Below we shall discuss various ways to enable the same:
- While using PHP 5 or a higher version on Windows, in order to install the Soap, all you have to do is visit the php.ini section and uncomment if the following extension prevails: extension=php_soap.dll. Once through, you would be able to see the installation when running the PHPINFO.
- Linux users can achieve the same by the following code – yum install php-soap
- PHP 4 users should make use of the nusoap for the same.
Creating the Web Service: The Actual Coding
In this example, we intend to create a web services dedicated to a library that would allow the users to search for books and authors and also browse the books written by a particular author.
The author is going to have the attributes, namely author_id, author_name and the book will comprise of book_id, book_name and author_id.
For the sake of simplicity, we are considering that at any point, the given writer has written only one book.
Coding for the WSDL File
The code required for creating a WSDL file is mentioned below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
<?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> |
There are 4 primary parts included in the WSDL File, namely:
1.Types – It defines the types which are going to be included in the program, much like defining the variations in a random PASCAL program.
2.Messages – Every function mentioned in this section has two messages primarily. One is destined for the input stream and other for the output. Besides, there is a provision for exception handling, as you get to add one extra message for the same.
3.Port Type – With the help of this feature, you get to combine one or more messages for representing the function. For instance, in the “Search Books” category, we would have to unite two different messages, one belonging to the input and other to our response.
4.Binding – Lastly, the binding section takes care of defining the details of the protocol in the web services that we are creating.
Now, we will create two different classes, one to contain the data regarding the books and other dedicated to the authors. Here, please note to keep the same name of the members, which you already specified in the WSDL file.
Class Containing the Book Data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php class BookData { public $ID; public $NAME; public $AUTHOR; } ?> Class containing Author Data <?php class BookData { public $ID; public $NAME; public $BOOKS; } ?> |
Now we shall create a Wrapper Class:
Book Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
<?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;$i<$NumOfBooks;$i++){ $Author = new AuthorData(); $Author->ID=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;$i<$NumOfAuthors;$i++){ $Author = new AuthorData(); $Author->ID=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;$i<$NumOfBooks;$i++){ $Book = new BookData(); $Book->ID=mysql_result($Query, $i,"books.book_id"); $Book->NAME=mysql_result($Query, $i,"books.book_name"); $Result[]= $Book ; } return $Result; } } ?> |
Now the next step is to create a PHP file which would cater to all the requests from the SOAP clients and be responsible for returning the results. Also note that this is the same file which was written in SOAP action previously specified in the WSDL file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?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(); ?> |
Lastly, please not to create a map, which would link the classes holding the data and the complex types. To know more, please consider our example in which we mapped Book, which has a complex type and Book Data which is one of the PHP classes.
Hurray! We just completed developing the web services by using PHP Development Services. Now let us name it lib.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?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(); } ?> |
Congratulations on your successful completion of the same. Please share your views on our tutorial in the comments section below.
Author Bio: Celin is a passionate Web developer and an obsessive compulsive tech writer. She is working with a leading company providing Custom PHP Development Services. You may Hire PHP Programmers for your high end customized and bespoke projects.