Membuat dan Menjalankan Proyek Slim di ServBay
Dokumen ini akan memandu Anda bagaimana cara membuat, mengonfigurasi, dan menjalankan proyek Slim Framework berbasis PHP dengan cepat di ServBay, sebuah lingkungan pengembangan web lokal yang tangguh. ServBay menghadirkan paket PHP terintegrasi, web server (Caddy/Nginx/Apache), serta berbagai software database, sehingga menjadi platform ideal untuk pengembangan dengan Slim.
Apa itu Slim?
Slim adalah kerangka kerja mikro PHP yang ringan, dirancang untuk membangun aplikasi web dan API yang sederhana namun tetap powerful secara cepat. Ia menawarkan fungsionalitas inti seperti routing, pemrosesan request, dan response, sangat cocok untuk proyek yang membutuhkan pengembangan dan deploy kilat, atau sebagai fondasi aplikasi yang lebih kompleks.
Fitur dan Keunggulan Utama Slim
- Ringan: Library inti Slim sangat kecil, penggunaan sumber dayanya rendah, serta proses booting yang cepat, cocok untuk aplikasi skala kecil-menengah maupun microservice.
- Fleksibel: Slim dirancang pluggable, mudah terintegrasi dengan komponen pihak ketiga apa pun (seperti engine template, ORM, library autentikasi, dsb), memberi Anda kebebasan memilih tools paling sesuai dengan kebutuhan proyek Anda.
- Mudah Digunakan: API yang sederhana dan dokumentasi yang jelas membuat developer dapat memahami konsep inti dan langsung mulai coding dalam waktu singkat.
- Routing yang Kuat: Mendukung banyak metode HTTP (GET, POST, PUT, DELETE, dll.) dengan konfigurasi routing kompleks, termasuk grouping, middleware, hingga parameter capture.
- Dukungan Middleware: Layer middleware Slim memungkinkan Anda menjalankan tugas seperti autentikasi, logging, atau penanganan CORS sebelum request tiba ke aplikasi utama atau sebelum response dikirim ke klien.
Slim sangat ideal untuk membangun RESTful API, pengembangan prototipe cepat, serta penanganan fungsionalitas khusus secara terpisah.
Membuat dan Menjalankan Proyek Slim Menggunakan ServBay
Panduan berikut memanfaatkan lingkungan PHP bawaan ServBay dan fitur Website untuk pengaturan web server serta mengakses proyek Slim Anda dengan mudah.
Prasyarat
Sebelum memulai, pastikan Anda telah:
- Menginstal & Menjalankan ServBay: Pastikan ServBay telah terpasang dengan baik pada macOS Anda dan aplikasinya berjalan.
- ServBay Sudah Termasuk Composer: Composer sudah terintegrasi di ServBay, tidak perlu instalasi terpisah.
Membuat Proyek Slim
ServBay menyarankan untuk menempatkan semua proyek website di direktori /Applications/ServBay/www
, agar lebih mudah dalam pengelolaan dan konfigurasi.
- Masuk ke root website ServBay:bash
cd /Applications/ServBay/www
1 - Buat directory project: Buat folder baru untuk menampung proyek Slim Anda.bash
mkdir servbay-slim-app
1 - Masuk ke folder project:bash
cd servbay-slim-app
1 - Instalasi Slim dengan Composer: Jalankan Composer di direktori proyek untuk menginstal kerangka Slim dan implementasi PSR-7.bashPerintah ini akan mengunduh Slim Framework beserta library
composer require slim/slim "^4.0" slim/psr7 -W
1slim/psr7
ke foldervendor
dan menghasilkancomposer.json
sertacomposer.lock
.
Inisialisasi Aplikasi Slim
- Buat file entry point: Proyek Slim umumnya memakai satu file masuk, misal
public/index.php
, untuk menangani seluruh request. Buat folderpublic
, lalu fileindex.php
di dalamnya.bashmkdir public touch public/index.php
1
2 - Edit file entry point: Buka dan isi
public/index.php
dengan kode Slim dasar berikut:phpKode di atas membuat Slim app sederhana dengan satu route (GET<?php // Memuat file autoload Composer require __DIR__ . '/../vendor/autoload.php'; // Import interface PSR-7 dan kelas factory Slim use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; // Membuat instance aplikasi Slim $app = AppFactory::create(); // Tambahkan routing dasar: handle GET ke root path '/' $app->get('/', function (Request $request, Response $response, $args) { // Menulis pesan ke response body $response->getBody()->write("Hello ServBay!"); // Mengembalikan objek response return $response; }); // Jalankan aplikasi Slim $app->run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/
) yang akan mengembalikan response bertuliskan "Hello ServBay!".
Konfigurasi Website di ServBay
Agar bisa diakses melalui browser, Anda perlu menambahkan Website pada ServBay (di versi lama disebut "Host").
- Buka antarmuka aplikasi ServBay.
- Navigasikan ke modul Website.
- Klik untuk menambah website baru.
- Isi konfigurasi berdasarkan proyek Anda:
- Name:
My First Slim Dev Site
(atau nama lain sesuai keinginan) - Domain:
servbay-slim-test.local
(disarankan gunakan.local
atau.test
untuk domain pengembangan lokal) - Website Type:
PHP
- PHP Version: Pilih versi PHP yang dibutuhkan, misal
8.3
. - Document Root: Klik "browse", lalu pilih direktori
public
dari proyek Anda, yaitu/Applications/ServBay/www/servbay-slim-app/public
. Karena file entry pointindex.php
ada di folder ini, maka web server harus diarahkan ke sini.
- Name:
- Simpan konfigurasi website. ServBay akan memperbarui dan mengaktifkan setup web server secara otomatis.
Untuk langkah lebih detail, silakan lihat Menambah Website Pertama.
Mengakses Website Slim Anda
Setelah konfigurasi, buka browser dan kunjungi domain yang Anda tentukan, misal https://servbay-slim-test.local
.
Jika berhasil, Anda akan melihat halaman dengan teks Hello ServBay!
, yang berarti aplikasi Slim berjalan melalui web server ServBay.
Contoh Integrasi Database
Slim sendiri tidak menyertakan data abstraction layer, namun sangat mudah mengintegrasikan library database PHP apa saja. Di sini akan dicontohkan menggunakan Eloquent ORM Laravel (illuminate/database
) untuk koneksi ke MySQL dan PostgreSQL, serta contoh integrasi Memcached dan Redis.
Prasyarat: Membuat Database & Migrasi
Sebelum integrasi, Anda harus membuat database di ServBay dan menyiapkan struktur tabel aplikasi Anda.
- Membuat database:
- Buka antarmuka ServBay, lalu masuk ke modul database (misal MySQL atau PostgreSQL).
- Pakai alat administrasi ServBay (phpMyAdmin untuk MySQL/MariaDB, pgAdmin untuk PostgreSQL) atau client CLI untuk membuat database baru—misal
servbay_slim_app
. - Password default root database biasanya
password
; Anda bisa cek atau ubah dari panel ServBay.
- Instal & Konfigurasi Phinx (alat migrasi database): Phinx adalah tool migrasi database PHP untuk versioning struktur database.
- Dari folder proyek
/Applications/ServBay/www/servbay-slim-app
, install Phinx via Composer:bashcomposer require robmorgan/phinx
1 - Inisialisasi konfigurasi Phinx:bashAkan membuat file
vendor/bin/phinx init
1phinx.yml
pada root proyek. Edit file ini untuk mengisi data koneksi database Anda, seperti:yamlpaths: migrations: '%%PHINX_CONFIG_DIR%%/db/migrations' seeds: '%%PHINX_CONFIG_DIR%%/db/seeds' environments: default_migration_table: phinxlog default_environment: development # atau nama lingkungan Anda development: # atur sesuai jenis database adapter: mysql # atau pgsql host: 127.0.0.1 name: servbay_slim_app # nama database user: root pass: password # password database port: 3306 # Default MySQL, PostgreSQL 5432 charset: utf8mb4 # untuk MySQL collation: utf8mb4_unicode_ci # untuk MySQL version_order: creation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- Dari folder proyek
- Buat file migrasi: Pakai perintah Phinx untuk membuat migrasi baru.bashFile PHP baru akan dibuat di
vendor/bin/phinx create CreateUsersTable
1db/migrations
. Edit methodchange()
di file itu seperti berikut:php<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateUsersTable extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method * * Remember to call "create()" or "update()" and NOT "save()" when working * with the Table class. */ public function change(): void { $table = $this->table('users'); $table->addColumn('name', 'string') ->addColumn('email', 'string', ['unique' => true]) ->addTimestamps() // Menambah field created_at dan updated_at ->create(); } }
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 - Jalankan migrasi: Di root proyek, jalankan Phinx untuk mengeksekusi migrasi dan menciptakan tabel
users
.bashPenting: Pastikan langkah migrasi dan pembuatan database selesai sebelum lanjut ke contoh kode di bawah.vendor/bin/phinx migrate
1
Menggunakan Komponen illuminate/database
Kita akan gunakan komponen database Laravel (illuminate/database
) sebagai ORM dan query builder.
Instal illuminate/database: Install pada root proyek
/Applications/ServBay/www/servbay-slim-app
.bashcomposer require illuminate/database
1Inisialisasi koneksi database di
public/index.php
: Tambahkan kode berikut di fileindex.php
, tepat setelah barisrequire __DIR__ . '/../vendor/autoload.php';
dan sebelum$app = AppFactory::create();
.php// ... require dan use lainnya ... use Illuminate\Database\Capsule\Manager as Capsule; // Import Capsule Manager // Inisialisasi Eloquent ORM $capsule = new Capsule; // Tambahkan konfigurasi koneksi database (ubah driver dan detail sesuai kebutuhan Anda) $capsule->addConnection([ 'driver' => 'mysql', // atau 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', // nama database Anda 'username' => 'root', // user DB 'password' => 'password', // password DB 'charset' => 'utf8mb4', // direkomendasikan MySQL 'collation' => 'utf8mb4_unicode_ci', // direkomendasikan MySQL 'prefix' => '', // Untuk PostgreSQL, tambahkan parameter schema // 'schema' => 'public', ]); // Buat global yang bisa diakses seluruh aplikasi $capsule->setAsGlobal(); // Instruksikan Eloquent untuk boot $capsule->bootEloquent(); // ... kemudian buat instance Slim ($app = AppFactory::create();) ...
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
Contoh MySQL
Dengan asumsi MySQL sudah dinyalakan di ServBay, database servbay_slim_app
sudah dibuat, dan migrasi users
telah dijalankan.
Tambahkan route berikut ke dalam public/index.php
sebelum $app->run();
:
php
// ... kode inisialisasi sebelumnya dan route '/' ...
use Illuminate\Database\Capsule\Manager as Capsule; // Pastikan sudah diimpor
// Route untuk menambah user
$app->get('/mysql-add-user', function (Request $request, Response $response, $args) {
try {
Capsule::table('users')->insert([
'name' => 'ServBay Demo User',
'email' => 'servbay-demo-' . time() . '@servbay.test', // jamin email unik
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$response->getBody()->write('User added to MySQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500); // Kode status error
}
return $response;
});
// Route untuk mengambil data user
$app->get('/mysql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson()); // Output dalam format JSON
$response = $response->withHeader('Content-Type', 'application/json'); // Set Content-Type
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... $app->run();
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
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
Akses:
- Akses
https://servbay-slim-test.local/mysql-add-user
untuk menambah user ke tabelusers
. - Akses
https://servbay-slim-test.local/mysql-get-users
untuk mendapatkan semua user dalam bentuk JSON.
Contoh PostgreSQL
Jika Anda sudah mengaktifkan PostgreSQL di ServBay, membuat database dan tabel sesuai instruksi (pastikan adapter
di Phinx di-set pgsql
dan port 5432
):
Gantilah konfigurasi koneksi di public/index.php
, pada bagian driver
gunakan pgsql
dan tambahkan schema
:
php
$capsule->addConnection([
'driver' => 'pgsql', // Ganti ke pgsql
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8', // Disarankan untuk PostgreSQL
'prefix' => '',
'schema' => 'public', // Wajib pada PostgreSQL
]);
// ... bagian Eloquent lainnya tetap ...
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Tambahkan route berikut di public/index.php
sebelum $app->run();
:
php
// ... kode inisialisasi sebelumnya dan route '/' ...
// ... idealnya MySQL route juga di sini jika diperlukan ...
use Illuminate\Database\Capsule\Manager as Capsule; // Pastikan sudah diimpor
// Route untuk menambah user ke PostgreSQL
$app->get('/pgsql-add-user', function (Request $request, Response $response, $args) {
try {
Capsule::table('users')->insert([
'name' => 'ServBay PG Demo User',
'email' => 'servbay-pg-demo-' . time() . '@servbay.test', // jamin email unik
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$response->getBody()->write('User added to PostgreSQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// Route untuk mendapatkan data user dari PostgreSQL
$app->get('/pgsql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson());
$response = $response->withHeader('Content-Type', 'application/json');
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... $app->run();
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
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
Akses:
- Akses
https://servbay-slim-test.local/pgsql-add-user
untuk menambah user ke tabelusers
di PostgreSQL. - Akses
https://servbay-slim-test.local/pgsql-get-users
untuk mendapat user sebagai JSON dari PostgreSQL.
Contoh Memcached
ServBay menyediakan paket Memcached dan ekstensi PHP ext-memcached
. Anda hanya perlu menginstal library klien PHP seperti memcached/memcached
.
Instal library klien Memcached: Di root proyek
/Applications/ServBay/www/servbay-slim-app
.bashcomposer require memcached/memcached
1Tambah route Memcached di
public/index.php
: Tempatkan sebelum$app->run();
.php// ... kode inisialisasi & route database sebelumnya ... // Route menggunakan Memcached $app->get('/memcached-example', function (Request $request, Response $response, $args) { // Buat instance klien Memcached $memcached = new Memcached(); // Tambah server Memcached (default ServBay ada di 127.0.0.1:11211) $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_servbay_cache_key'; // Coba ambil data dari cache $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { // Jika cache tidak ditemukan, buat data baru dan simpan di cache $cachedData = 'Hello Memcached from ServBay! This was not cached.'; // Simpan ke cache selama 60 detik $memcached->set($cacheKey, $cachedData, 60); $response->getBody()->write($cachedData); } else { // Jika ditemukan di cache, gunakan cache $response->getBody()->write('Hello Memcached from ServBay! This was served from cache.'); } return $response; }); // ... $app->run();
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
Akses: Buka https://servbay-slim-test.local/memcached-example
. Akses pertama akan menampilkan "This was not cached.", akses berikutnya (selama cache belum kedaluwarsa) akan menampilkan "This was served from cache.".
Contoh Redis
ServBay juga menyediakan Redis serta ekstensi PHP ext-redis
. Anda hanya perlu install klien PHP misal predis/predis
.
Instal library klien Redis: Dari root proyek
/Applications/ServBay/www/servbay-slim-app
.bashcomposer require predis/predis
1Tambah route Redis di
public/index.php
: Tempatkan sebelum$app->run();
.php// ... kode inisialisasi lain & route database ... // ... route Memcached apabila diperlukan ... use Predis\Client as RedisClient; // Impor library Predis // Route menggunakan Redis $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // Buat instance klien Redis (default di ServBay: 127.0.0.1:6379) $redis = new RedisClient([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_servbay_redis_cache_key'; // Coba ambil data dari cache $cachedData = $redis->get($cacheKey); if ($cachedData === null) { // Jika cache belum ada, buat data dan simpan ke Redis $cachedData = 'Hello Redis from ServBay! This was not cached.'; // Simpan ke cache Redis selama 60 detik $redis->setex($cacheKey, 60, $cachedData); // SETEX key seconds value $response->getBody()->write($cachedData); } else { // Jika sudah ada di cache $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // Tangani exception koneksi atau operasi Redis $response->getBody()->write('Error connecting to Redis or performing operation: ' . $e->getMessage()); $response = $response->withStatus(500); } return $response; }); // ... $app->run();
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
Akses: Kunjungi https://servbay-slim-test.local/redis-example
. Kunjungan pertama tampilkan "This was not cached.", berikutnya (sebelum cache expired) tampilkan "This was served from cache.".
Kesimpulan
Dengan mengikuti langkah-langkah di atas, Anda telah berhasil membuat proyek Slim Framework di lingkungan lokal ServBay, mengkonfigurasi fitur Website untuk hosting dan akses, serta mempelajari cara integrasi berbagai Software Package ServBay (MySQL, PostgreSQL, Memcached, Redis) beserta ekstensi PHP-nya ke dalam aplikasi Slim Anda. ServBay mempermudah penyiapan dan pengelolaan lingkungan dev lokal sehingga Anda dapat lebih fokus pada pengembangan aplikasi Slim itu sendiri.