PHP : Membuat REST API dengan Slim Framework
Intro
Slim Framework adalah microframework PHP yang dapat digunakan untuk membuat REST API. Slim Framework relatif mudah dipelajari dan sederhana konfigurasinya, namun bila membutuhkan tambahan seperti security layer masih susah kalau memakai Slim Framework. Alternatif lain untuk membuat REST API menggunakan PHP di antaranya adalah menggunakan Lumen yang "sekeluarga" dengan Laravel.
Membuat Database
Buat database dengan nama db_kuliah
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE DATABASE db_kuliah; | |
CREATE TABLE `tbl_mahasiswa` ( | |
`nim` varchar(10) NOT NULL, | |
`nama` varchar(60) NOT NULL, | |
`alamat` varchar(300) DEFAULT NULL | |
); | |
INSERT INTO `tbl_mahasiswa` (`nim`, `nama`, `alamat`) VALUES | |
('M1453277', 'mahasiswa 1', 'Solo'), | |
('M1453278', 'mahasiswa 2', 'Klaten'), | |
('M1453279', 'mahasiswa 3', 'Sukoharjo'); |
Install Composer
Untuk dapat menggunakan Slim Framework, terlebih dahulu harus menginstall composer. Composer adalah tool dependency manager (tool untuk mendownload library / framework PHP). Tata cara instalasi composer dapat dibaca di https://getcomposer.org/download.Install Slim Framework
Buat folder untuk menyimpan file-file web service + Slim Framework Masuk ke folder yang telah dibuat sebelumnya, install Slim Framework menggunakan perintahcomposer require slim/slim "^3.0"
Buat file classes/Mapper.php dengan isi script sebagai berikut
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// abstract class PHP untuk memuat object db | |
// dari class ini diturunkan ke class lain untuk melakukan query db | |
abstract class Mapper { | |
protected $db; | |
public function __construct($db) { | |
$this->db = $db; | |
} | |
} |
Buat file classes/MahasiswaMapper.php, file ini digunakan untuk melakukan query database. Hasil query database nantinya akan diakses melalui alamat URL web service oleh aplikasi lain misalnya aplikasi Android. Isi script classes/MahasiswaMapper.php adalah sebagai berikut
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// class untuk melakukan query db ke tabel tbl_mahasiswa | |
class MahasiswaMapper extends Mapper | |
{ | |
// mengambil semua record di tbl_mahasiswa | |
public function getAllMhs() { | |
$sql = "SELECT * from tbl_mahasiswa"; | |
$stmt = $this->db->query($sql); | |
$results = $stmt->fetchAll(); | |
return $results; | |
} | |
// mengambil record dari tbl_mahasiswa berdasarkan nim mahasiswa | |
public function getMahasiswaByNim($nim) { | |
$sql = "SELECT * from tbl_mahasiswa where nim = :nim"; | |
$stmt = $this->db->prepare($sql); | |
$result = $stmt->execute(["nim" => $nim]); | |
if($result) { | |
return $stmt->fetch(); | |
} | |
} | |
// memasukkan data mahasiswa baru ke tbl_mahasiswa | |
public function saveMahasiswa($nim, $nama, $alamat) { | |
$sql = "insert into tbl_mahasiswa | |
(nim, nama, alamat) values | |
(:nim, :nama, :alamat)"; | |
$stmt = $this->db->prepare($sql); | |
$result = $stmt->execute([ | |
"nim" => $nim, | |
"nama" => $nama, | |
"alamat" => $alamat, | |
]); | |
if(!$result) { | |
throw new Exception("could not save record"); | |
} | |
} | |
// mengupdate data mahasiswa | |
public function updateMahasiswa($old_nim, $nim, $nama, $alamat) { | |
$sql = "update tbl_mahasiswa set nim = :nim, nama = :nama, alamat = :alamat where nim = :old_nim"; | |
$stmt = $this->db->prepare($sql); | |
$result = $stmt->execute([ | |
"old_nim" => $old_nim, | |
"nim" => $nim, | |
"nama" => $nama, | |
"alamat" => $alamat, | |
]); | |
if(!$result) { | |
throw new Exception("could not update record"); | |
} | |
} | |
// menghapus data mahasiswa | |
public function deleteMahasiswa($nim) { | |
$sql = "delete from tbl_mahasiswa where nim = :nim"; | |
$stmt = $this->db->prepare($sql); | |
$result = $stmt->execute([ | |
"nim" => $nim | |
]); | |
if(!$result) { | |
throw new Exception("could not delete record"); | |
} | |
} | |
} |
Buat file index.php untuk membuat URL dengan isi script sebagai berikut
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use \Psr\Http\Message\ServerRequestInterface as Request; | |
use \Psr\Http\Message\ResponseInterface as Response; | |
require __DIR__ . '/vendor/autoload.php'; | |
$config['addContentLengthHeader'] = false; | |
$config['displayErrorDetails'] = true; | |
// host atau alamat server mysql, bisa gunakan ip address | |
$config['db']['host'] = "localhost"; | |
// username mysql | |
$config['db']['user'] = "username"; | |
// password mysql | |
$config['db']['pass'] = "password"; | |
// nama database | |
$config['db']['dbname'] = "db_kuliah"; | |
$app = new \Slim\App(["settings" => $config]); | |
$container = $app->getContainer(); | |
// memasukkan setting db | |
$container['db'] = function ($c) { | |
$db = $c['settings']['db']; | |
$pdo = new PDO("mysql:host=" . $db['host'] . ";dbname=" . $db['dbname'], | |
$db['user'], $db['pass']); | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); | |
return $pdo; | |
}; | |
/* URL http://[host]/[namafolder] | |
method GET | |
menampilkan tulisan API Mahasiswa */ | |
$app->get('/', function(){ | |
echo "API Mahasiswa"; | |
}); | |
/* URL http://[host]/[namafolder]/mahasiswa/all | |
method GET | |
menampilkan data semua mahasiswa dari database */ | |
$app->get('/mahasiswa/all', function(){ | |
$mapper = new MahasiswaMapper($this->db); | |
$mahasiswa = $mapper->getAllMhs(); | |
return json_encode($mahasiswa); | |
}); | |
/* URL http://[host]/[namafolder]/mahasiswa/{nim} | |
method GET | |
menampilkan mahasiswa sesuai nim yang dimaksud */ | |
$app->get('/mahasiswa/{nim}', function (Request $request, Response $response, $args) { | |
$mapper = new MahasiswaMapper($this->db); | |
$mahasiswa = $mapper->getMahasiswaByNim($args['nim']); | |
return json_encode($mahasiswa); | |
}); | |
/* URL http://[host]/[namafolder]/mahasiswa/new | |
method POST | |
menambahkan data mahasiswa | |
pakai header | |
Content-type: application/json | |
contoh request body | |
{ | |
"nim":"m2", | |
"nama":"nama2", | |
"alamat":"alamat2" | |
} | |
*/ | |
$app->post('/mahasiswa/new', function (Request $request, Response $response) { | |
$data = $request->getParsedBody(); | |
$mapper = new MahasiswaMapper($this->db); | |
$mapper->saveMahasiswa($data['nim'], $data['nama'], $data['alamat']); | |
$obj = (object) [ | |
'status' => strval($response->getStatusCode()) | |
]; | |
echo json_encode($obj); | |
}); | |
/* URL http://[host]/[namafolder]/mahasiswa/update/{old_nim} | |
method PUT | |
mengubah data mahasiswa sesuai nim yang dimaksud | |
pakai header | |
Content-type: application/json | |
contoh request body | |
{ | |
"nim":"m3", | |
"nama":"nama2", | |
"alamat":"alamat3" | |
} | |
"old_nim":"m3" | |
old_nim ditambahkan ke url | |
*/ | |
$app->put('/mahasiswa/update/{old_nim}', function (Request $request, Response $response, $args) { | |
$data = $request->getParsedBody(); | |
$mapper = new MahasiswaMapper($this->db); | |
$mapper->updateMahasiswa($args['old_nim'], $data['nim'], $data['nama'], $data['alamat']); | |
$obj = (object) [ | |
'status' => strval($response->getStatusCode()) | |
]; | |
echo json_encode($obj); | |
}); | |
/* URL http://[host]/[namafolder]/mahasiswa/{nim} | |
method DELETE | |
menghapus mahasiswa sesuai nim yang dimaksud */ | |
$app->delete('/mahasiswa/{nim}', function (Request $request, Response $response, $args) { | |
$mapper = new MahasiswaMapper($this->db); | |
$mahasiswa = $mapper->deleteMahasiswa($args['nim']); | |
$obj = (object) [ | |
'status' => strval($response->getStatusCode()) | |
]; | |
echo json_encode($obj); | |
}); | |
$app->run(); |
Ubah file composer.json, ketik
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"slim/slim": "^3.0" | |
}, | |
"autoload": { | |
"psr-4": { | |
"": "classes/" | |
} | |
} | |
} |
Ketik perintah
composer dump-autoloadAgar file php di dalam folder classes dimuat secara otomatis oleh framework
Comments
Post a Comment