Introduction to API and PHP Basics
Introduction to API and PHP Basics
PROGRAMMING
INTERFACE (API)
Mohd Jasni bin Daut
[Link]@[Link]
019-280 1305
PENGENALAN
Objektif: Mengenali apa itu API dari segi terminologi, konsep dan kegunaannya.
2
CONTOH API JENIS-JENIS API
Jenis API atau arkitektur yang popular dibangunkan - REST vs SOAP
REST SOAP
3
KAEDAH PANGGILAN API FORMAT (RESPONSE) DATA API
Protokol yang biasa digunakan adalah Protokol yang biasa digunakan:
HTTP - POST vs GET json VS XML
*Lain-lain: FTP, PUT, DELETE, customs *Lain-lain: Plaintex, HTML, customs
Sample JSON:
Sample Code HTTP POST:
{
POST /test HTTP/1.1 "Id": 78912,
Host: [Link] "Customer": "Jason Sweet",
Content-Type: application/x-www-form-urlencoded "Quantity": 1,
Content-Length: 27 "Price": 18.00
}
field1=value1&field2=value2
<Data>
<Id>78912</Id>
GET /?field1=value1&field2=value2 HTTP/1.1 <Customer>Jason Sweet</Customer>
Host: [Link] <Quantity>1</Quantity>
<Price>18.00</Price>
</Data>
4
PENGENALAN KEPADA PHP
Objektif: Mengenali apa itu PHP dari segi terminology, Bahasa dan kegunaanya.
WHY PHP?
03 • Senang diselenggara - runs almost at all environment OS
User/data
DASHBOARD management, statistics, 02
server monitoring
6
POPULARITY
7
ASAS BAHASA PENGATURCARAAN PHP
Asas Bahasa
Kod Bahasa pengaturcaraan yang selalu digunakan
Iteration (Looping)
1 PHP Tags for statement 6
Arithmetic
3 Variables
operators 8
4 Arrays Functions 9
<?php <?php
echo "Hello world"; echo "Hello world";
// the script ends here with PHP closing tag // the script ends here with no PHP closing tag
?>
Di dalam HTML pula, ia mesti dimulakan dengan <?php dan mesti berakhir dengan ?> :
Sample Code:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
9
Comments • PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:
2 //,/**/,# statement
Sample Code:
<?php
echo 'This is a test'; // This is a one-line c++ style
comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style
comment
?>
10
• Declarations fof the variables:
3 Variables
Sample Code:
<?php
$a_str = "foo"; // a string using ""
$a_str2 = 'foo'; // a string using ''
$a_longstr = "foo this has long string"; // a long string using ""
$a_longstr2 = 'foo this also long string'; // a string using ''
$an_int = 12; // an integer
$a_double = 12.5; // a double
$a_money = 12.5; // a money
$a_bool = TRUE; // a boolean
Sample Code:
<?php
/* Creating new arrays:- */
//Creates a blank array.
$theVariable = array();
/*
Note:
New value can be added to the array as shown below.
*/
$theVariable[] = "D";
$theVariable[] = "E";
/**
To access an array:
*/
echo $theVariable[0] . "\r\n";
/**
To view array (for debugging):
*/
var_dump($theVariable);
?>
12
• It allows for conditional execution of code fragments. PHP features an if
Condition if…else
5 statement
structure that is similar to that of C:
Sample Code:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) { //using elseif (no space)
echo "a is equal to b";
} else if ($a == $b) { // using else if (has space)
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
13
Iteration (Looping) • The for loop - Loops through a block of code a specified number of
for statement 6 times:
Sample Code:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x \r\n";
}
?>
14
Iteration (Looping) • The foreach loop - Loops through a block of code for each element in
foreach statemnet 7 an array:
Sample Code:
<?php
$colors = array("red", "green", "blue",
"yellow");
15
Arithmetic
operators 8 • Remember basic arithmetic from school? These work just like those:
Sample Code:
<?php
$a = 2; // $a is equal 2
echo "a : $a" . "\r\n"; //print out 2
$a = 2 + 1; // $a is equal 3
echo "a : $a" . "\r\n"; //print out 3
$a = 6; // $a is equal 6
$b = 7; // $b is equal 7
echo "a : $a" . "\r\n"; //print out 6
echo "b : $b" . "\r\n"; //print out 7
?>
16
Arithmetic
operators 8 • Remember basic arithmetic from school? These work just like those:
Sample Code:
<?php
$a = 2; // $a is equal 2
$b = 3; // $b is equal 3
echo "a : $a" . "\r\n"; //print out 2
echo "b : $b" . "\r\n"; //print out 3
?>
17
Functions 9 • Besides the built-in PHP functions, it is possible to create your own functions:
Sample Code:
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year
";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
18
Classes
statement
10 • A class is a template for objects, and an object is an instance of class:
Sample Code:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "\r\n";
echo $banana->get_name();
?>
19
PENGENALAN KEPADA CODELGNITER
Objektif: Mengenali apa itu Codelgniter dan cara menggunakannya
Framework
Ia adalah PHP framework yang ringan dan mudah untuk dipelajari:
01 02 03 04 05
20
MVC: •
•
M is Model - manage data (database)
V is Views - User Interface
• C is Controller - control Model and Views*
21
How to installed it?
Please follow these steps:
04
'[Link] (taip port
[Link] jika ada),
anda sepatutnya dapat melihat paparan
seperti ini:
23
Pembangunan API menggunakan CodeIgniter
Objektif: Mula belajar membangunkan API dengan CodeIgniter.
Penting!
Pastikan anda menggunakan langkah ini:
24
Number 1: Number 4:
Number 2: Number 5:
API yang akan Boleh menyemak bil
REST dan menggunakan
protokol HTTP POST dibangunkan: dengan menghantar
parameter sama ada No.
IC atau No. Akaun atau
kedua-duanya
Number 3: Number 6:
25
Mula Bangunkan API
Ikuti langkah berikut:
[Link] phpMyAdmin (boleh taip di browser '[Link] atau buka melalui Control Panel XAMPP)
26
[Link] tab 'Import'
[Link] file '[Link]' yang telah diunzip tadi dan klik 'OK'
27
[Link] patut dapat melihat Database sudah berjaya diimport seperti ini:
28
[Link] applikasi Visual Studio Code
29
[Link] File > Open, pilih folder C:\xampp\htdocs\myfirstapi dan klik butang 'Open'
30
[Link] fail [Link], dan taip pada line 2:
date_default_timezone_set("Asia/Kuala_Lumpur");
31
[Link] fail application/config/[Link], dan taip URL seperti berikut pada line 26:
$config['base_url'] = '[Link]
$config['index_page'] = '';
32
[Link] fail application/config/[Link], dan taip seperti berikut pada line 61:
$autoload['libraries'] = array('database');
[Link] fail application/config/[Link], dan taip seperti berikut pada line 106:
$autoload['config'] = array('api');
33
[Link] fail application/config/[Link], dan taip seperti berikut bermula line 78:
[Link] fail baru dan 'Save As' sebagai '[Link]' di folder - application/config/[Link], dan taip seperti berikut:
<?php
defined('BASEPATH') OR exit('No direct script access
allowed');
$config['db_app'] = 'dbfirstapi';
$config['db_log'] = 'dbfirstapi';
34
[Link] fail baru dan 'Save As' sebagai 'MY_Controller.php' di folder - application/core/MY_Controller.php, dan taip seperti
berikut:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
public $timereq = 0;
public $billtype = 0;
function __construct(){
parent::__construct();
$this->benchmark->mark('xeostart');
$this->timereq = date('Y-m-d H:i:s');
}
35
[Link] fail baru dan 'Save As' sebagai '[Link]' di folder - application/controllers/[Link], dan taip seperti berikut:
37
[Link] fail baru dan 'Save As' sebagai 'Bill_model.php' di folder - application/models/Bill_model.php, dan taip seperti
berikut:
:
<?php
$addwhere = " ("; $sql = "SELECT
defined('BASEPATH') OR exit('No direct script access allowed');
if ($acno){ [Link] as `Nama`,
$temp = preg_replace('/[-\/]/','',$acno); [Link] as `NoKadPengenalan`,
class Bill_model extends CI_Model
[Link] as `NoTelefon`,
{
$opt1 = $temp; [Link] as `Emel`,
function __construct()
$opt2 = substr($temp, 0, -2) . '-' . substr($temp, -2); [Link] as `Emel`,
{
$opt3 = substr($temp, 0, 1) . '-' . substr($temp, 1, -2) . '-' . substr($temp, -2); [Link] as `NoAkaun`,
parent::__construct();
b.premaddress1 as `Address1`,
}
$addwhere .= " ({$field} = '{$opt1}') or ({$field} = '{$opt2}') or ({$field} = '{$opt3}')"; b.premaddress2 as `Address2`,
} b.premaddress3 as `Address3`,
private function prep_semak_icno($icno, $field='[Link]'){
$addwhere .= ") "; b.premaddress4 as `Address4`,
/**
[Link] as `Penerangan`,
* semak icno
return $addwhere; [Link] as `Semasa`,
*
} [Link] as `Tunggakan`,
* 800524071234 atau
[Link] as `Waran`,
* 800524-07-1234 atau
public function get_bill($icno='', $acno=''){ [Link] as `Denda`
*/
$this->db->db_select($this->config->item('db_log')); FROM sample_pelanggan a
try { LEFT JOIN sample_akaun b on [Link] = [Link]
$addwhere = " (";
$addwhere = ''; LEFT JOIN sample_bill c on [Link] = [Link]
if ($icno){
if (strlen($icno) && strlen($acno)){ WHERE [Link] = 1 and [Link] = 1 and [Link] = 1 {$addwhere}";
$temp = preg_replace('/[-\/]/','',$icno);
$addwhere .= " and " . $this->prep_semak_icno($icno, '[Link]');
$addwhere .= " and " . $this->prep_semak_acno($acno, '[Link]');
$opt1 = $temp;
}else if (strlen($icno)){ $query = $this->db->query($sql);
$opt2 = substr($temp, 0, 6) . '-' . substr($temp, 6, 2). '-' . substr($temp, -4);
$addwhere .= " and " . $this->prep_semak_icno($icno, '[Link]'); if ($query->num_rows() > 0){
}else if (strlen($acno)){ return $query->result_array();
$addwhere .= " ({$field} = '{$opt1}') or ({$field} = '{$opt2}')";
$addwhere .= ' and ' . $this->prep_semak_acno($acno, '[Link]'); }else{
}
}else{ return 0;
$addwhere .= ") ";
return 0; }
}
return $addwhere;
}catch (Exception $e){
}
return $e;
}
private function prep_semak_acno($acno, $field='[Link]'){
}
/**
* semak acno
}
*
* T010096457-07 atau
* T-010096457-07 atau
* T01009645707
*/
38
[Link] fail baru dan 'Save As' sebagai 'Client_model.php' di folder - application/models/Client_model.php, dan taip seperti
berikut:
<?php
defined('BASEPATH') OR exit('No direct script access allowed'); /** checking */
public function get_secret_key($clientid){
class Client_model extends CI_Model $this->db->db_select($this->config->item('db_app'));
{ $this->db->select("clientid");
function __construct() $this->db->where('clientid', $clientid);
{ $this->db->where('status', 1);
parent::__construct(); $query = $this->db->get('clients');
} if ($query->num_rows() > 0){
return true;
/** inserting */ }else{
public function save_client($data) return false;
{ }
$this->db->db_select($this->config->item('db_app')); }
$data['datecreated'] = date('Y-m-d H:i:s');
$data['timer'] = $this->benchmark->elapsed_time('xeostart'); }
$this->db->insert('clients', $data);
return $this->db->insert_id();
}
/** updating */
public function update_client($ref, $data, $success=0, $failed=0)
{
$this->db->db_select($this->config->item('db_app'));
$this->db->set('`trigger`', '`trigger`+1', FALSE);
$this->db->set('`success`', '`success`+' . $success, FALSE);
$this->db->set('`failed`', '`failed`+' . $failed, FALSE);
$data['dateupdated'] = date('Y-m-d H:i:s');
$this->db->update('clients', $data, $ref);
return $this->db->affected_rows();
}
39
[Link] fail baru dan 'Save As' sebagai 'Log_model.php' di folder - application/models/Log_model.php, dan taip seperti
berikut:
<?php
defined('BASEPATH') OR exit('No direct script access allowed'); $db = $this->db->query($sql); // table does not exist
$sql = "CREATE TABLE `{$tbl}` (
class Log_model extends CI_Model $keys = "ALTER TABLE `{$tbl}` `wid` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
{ ADD KEY `clientid` (`clientid`), `datecreated` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
function __construct() ADD KEY `service` (`service`), `timer` decimal(11,4) DEFAULT '0',
{ ADD KEY `code` (`code`), `type` int(11) DEFAULT '0',
parent::__construct(); ADD KEY `pkey` (`pkey`), `logid` int(11) DEFAULT '0',
} ADD KEY `skey` (`skey`), `clientid` int(11) DEFAULT '0',
ADD KEY `tkey` (`tkey`), `clienttype` int(11) DEFAULT '0',
/** creating */ ADD KEY `transid` (`transid`);"; `deviceid` int(11) DEFAULT '0',
public function create_log_tdr($date=null) `transid` int(11) DEFAULT '0',
{ $db = $this->db->query($sql); `userid` int(11) DEFAULT '0',
$tbl = "log_tdr_" . (($date) ? $date : date('Ym')); `ip` VARCHAR(20) NULL,
$this->db->db_select($this->config->item('db_log')); return $tbl; `service` int(11) DEFAULT '0',
} `code` int(11) DEFAULT '0',
if ($this->db->table_exists($tbl)) } `pkey` VARCHAR(20) NULL,
{ `skey` VARCHAR(20) NULL,
// table exists some code run query public function create_watchlist($date=null) `tkey` VARCHAR(20) NULL,
return 0; { `status` int(11) DEFAULT '0',
} $tbl = "watchlist_" . (($date) ? $date : date('Y')); `message` VARCHAR(40) NULL
else $this->db->db_select($this->config->item('db_log')); );";
{
// table does not exist if ($this->db->table_exists($tbl))
$sql = "CREATE TABLE `{$tbl}` ( {
`logid` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL, // table exists some code run query
`datecreated` timestamp NULL DEFAULT CURRENT_TIMESTAMP, return 0;
`timer` decimal(11,4) DEFAULT '0', }
`type` int(11) DEFAULT '0', else
`clientid` int(11) DEFAULT '0', {
`clienttype` int(11) DEFAULT '0',
`deviceid` int(11) DEFAULT '0',
`transid` int(11) DEFAULT '0',
`userid` int(11) DEFAULT '0',
`ip` VARCHAR(20) NULL,
`service` int(11) DEFAULT '0',
`code` int(11) DEFAULT '0',
`pkey` VARCHAR(20) NULL,
`skey` VARCHAR(20) NULL,
`tkey` VARCHAR(20) NULL,
`param` text NULL,
`output` mediumtext NULL,
`status` int(11) DEFAULT '0',
`message` VARCHAR(40) NULL,
`dateupdated` datetime NULL 40
);";
[Link] fail baru dan 'Save As' sebagai 'Log_model.php' di folder - application/models/Log_model.php, dan taip seperti
berikut:
41
[Link] applikasi Postman untuk menguji API dan lakukan seperti berikut:
1. Pilih 'POST’
2. Masukkan URL: [Link]
3. Pilih 'Body' dan pilih 'form-data’
4. Masukkan value seperti di dalam gambar
5. Tekan butang Send
6. Result sepatutnya seperti di dalam gambar (pilih pretty)
42
[Link], anda telah berjaya membangunkan API pertama anda menggunakan CodeIgniter!
CONGRATULATION!
43