What is RESTful Web Service API in PHP?
The objective is to build a RESTful web service in PHP to provide resource data based on the request with the network call by the external clients.
- Make the RESTful service to be capable of responding to the requests in JSON, XML, and HTML formats.
<?php
// A domain Class to demonstrate RESTful web services
class Mobile
{
private $mobiles = array(
1 => 'Apple iPhone 6S',
2 => 'Samsung Galaxy S6',
3 => 'Apple iPhone 6S Plus',
4 => 'LG G4',
5 => 'Samsung Galaxy S6 edge',
6 => 'OnePlus 2'
);
// you should hookup the DAO here
public function getAllMobile()
{
return $this->mobiles;
}
public function getMobile($id)
{
$mobile = array(
$id => ($this->mobiles[$id]) ? $this->mobiles[$id] : $this->mobiles[1]
);
return $mobile;
}
}
?>
SERVICE CONTROLLER :
<?php
require_once ("MobileRestHandler.php");
$view = "";
if (isset($_GET["view"]))
$view = $_GET["view"];
// controls the RESTful services
// URL mapping
switch ($view) {
case "all":
// to handle REST Url /mobile/list/
$mobileRestHandler = new MobileRestHandler();
$mobileRestHandler->getAllMobiles();
break;
case "single":
// to handle REST Url /mobile/show/<id>/
$mobileRestHandler = new MobileRestHandler();
$mobileRestHandler->getMobile($_GET["id"]);
break;
case "":
// 404 - not found;
break;
}
?>
- As an interface with multi-platform support which is used to access resources from outside applications coded in various programming languages like PHP, JAVA, Android and more.