Membuat Simple Web Service Dengan PHP ( PDO) + Json

By Budyks    PHP

Tutorial simple PHP kali akan membahas membuat Web service data Mahasiswa simple dengan PDO ( PHP Data Object). Sedikit tambahan, bahwa Web service itu berguna untuk mengakses/mengambil data dari Aplikasi luar tentunya dengan permission atau hak akses. 
Ok langsung saja kita mulai . Pertama siapkan databse dan table nya (mySQL) DB Name : test , Table : mhskira begini penampakan table nya. ( buat sendiri jg gampang kn :D)
id nama alamat umur
1 Ganjar St. Paris 89, Jakarta 24
2 Mimin

Jl. Sudnari asri no 90,Bandung

22
Persiapan folder dan file-file di htdocs
  1. koneksi.php
  2. mhs.php
  3. web_service.php
  4. akses_web_service.php
taruh file-file diatas di 1 folder misalnya 'web-service' di htdocs.
Sekarang kita buat satu-satu kode nya.
koneksi.php
class Koneksi {
    
    //DB name : test    protected $dns   = "mysql:host=localhost;dbname=test";     protected $db_user        = "root";    protected $db_pass     = "";    protected $konek   = "";           public function getKon() {                try{                              $db = new PDO($this->dns,$this->db_user,$this->db_pass);   $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    if($db===FALSE){                           throw new Exception("Koneksi Gagal");                                }else{                            $this->konek = $db;    }                     }catch(Exception $e){                      echo "Error : ".$e->getMessage();     }
   return $this->konek;   }     public function closeKon(){                 $this->konek = NULL; //diskonek Koneksi    }}

/*
Kita sekalian buat Class active record simple
untuk fetch data ke DB */
class ActiveRecord extends Koneksi{            public function fetchObject($sql){          $clone = array();               try{
      $data =  $this->getKon()->prepare($sql);         $data->setFetchMode(PDO::FETCH_INTO,$this);      $data->execute(); 

           /* krena fetch ingin sbg Object, 
            maka kita hrus clone hasilnya */          while($result = $data->fetch()){                                          $clone[] = clone $result;      }
      $this->closeKon();                        }catch(PDOException $e){                          echo $e->getMessage();       }   
       return $clone;
   }}
mhs.php
require_once "koneksi.php";

class MhsWebService{
    
    protected $name;
    protected $umur;
    
    //misal API yg dikasih utk client
    protected $API = 'khss8363621';
    
    public function setName($name){
        
        $this->name = $name;
    }
    public function getName(){
        
        return $this->name;
    }
    
    public function setUmur($umur){
        
        $this->umur = $umur;
    }
    public function getUmur(){
        
        return $this->umur;
    }
    
    public function validateAPI($api){
        
        if($this->API !== $api)
            return false;
            
        return true;
    }
    
    
    public function getMhs(){
                                        
       $objAr= new ActiveRecord();
       
       /*Query blm pake bind params, silahkan edit sendiri*/
       $sql = "SELECT * FROM mhs WHERE 1=1  ";
          if($this->getName()){
                    
              $sql .=" AND nama LIKE '%{$this->getName()}%' ";
          }
          if($this->getUmur()){

            $sql .=" AND umur LIKE '%{$this->getUmur()}%' ";
          }
                
      return $objAr->fetchObject($sql);
       
    }   
}
web_service.php
validateAPI($s_API)){
    
    //kirim params" nya
    $mhs->setName($s_name);
    $mhs->setUmur($s_umur);
    
    $data = $mhs->getMhs();
    //print_r($data);
    reset($data);
    $i=0;
    //saya pake while, klo mau foreach silahkan :D
    while(list(,$r) =  each($data)){
        
        $hasil[$i]['nama'] = $r->nama;
        $hasil[$i]['umur'] = $r->umur;
        $hasil[$i]['alamat'] = $r->alamat;
        
        ++$i;
    }
   
   //hanya utk flag saja
   $hasil['status'] = TRUE;
    
}else{
    
    $hasil['status'] = FALSE;
}

echo json_encode($hasil);

?>
akses_web_service.php

    
       
    
    
        
        

MHS Web Service


Name : Umur :
$s_name, 'umur' => $s_umur ); $data = http_build_query($fields); $context = stream_context_create(array( 'http' => array( 'method' => 'GET', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $data, ) )); $result = file_get_contents($url, false, $context); //decode json nya ke array $vr = json_decode($result,true); echo "
";
                    print_r($vr);
                echo "
"; } ?>
Di atas terlihat saya pakai file_get_contents   , silahkan gunakan method yg lain jika perlu. 
Output dari program diatas seperti ini
Masih dalam Array biasa, silahkan proses sendiri :D
Akses aplikasinya di browser
localhost/web-service/akses_web_service.php
Begitulah kira-kira :D
Happy Coding !!!!

Comments



    Follow Us