Cara Mencipta & Menjalankan Projek Slim di ServBay
Dokumen ini akan membantu anda langkah demi langkah untuk membina, mengkonfigurasi dan melancarkan projek PHP menggunakan Slim Framework secara tempatan dalam persekitaran pembangunan web ServBay yang serba lengkap. ServBay membekalkan pakej PHP, pelayan web (Caddy/Nginx/Apache) serta pelbagai perisian pangkalan data – menjadikannya platform ideal untuk pembangunan Slim Framework.
Apa itu Slim?
Slim merupakan micro-framework PHP yang ringan, direka khusus untuk membina aplikasi web dan API yang pantas, ringkas tetapi berkuasa. Ia menyediakan fungsi utama seperti routing, pengendalian request dan response, sesuai untuk projek yang perlu dikembangkan atau dideploy dengan cepat, serta sebagai asas aplikasi yang lebih kompleks.
Ciri-ciri & Kelebihan Utama Slim
- Ringan: Kod teras Slim adalah kecil dan penggunaan memori rendah, memulakan aplikasi dengan pantas – sesuai untuk microservice atau aplikasi berskala kecil dan sederhana.
- Fleksibel: Reka bentuk modular membolehkan integrasi lancar dengan sebarang komponen atau pustaka PHP pihak ketiga (seperti engine template, ORM, pustaka auth, dsb.), memberi kebebasan memilih alat terbaik untuk keperluan projek anda.
- Mudah digunakan: API yang ringkas serta dokumentasi jelas membolehkan pembangun cepat memahami konsep teras dan mula membina aplikasi.
- Routing berkuasa: Menyokong pelbagai method HTTP (GET, POST, PUT, DELETE dan lain-lain), konfigurasi routing yang rumit, termasuk pengelompokan route, middleware dan parameter dinamik.
- Sokongan Middleware: Lapisan middleware Slim membolehkan anda jalankan tugas seperti pengesahan, logging, pengurusan CORS sebelum atau selepas request dikendalikan.
Slim sangat sesuai untuk membina RESTful API, rapid prototyping, serta aplikasi modul atau fungsi khusus yang bebas.
Langkah-langkah Membina & Menjalankan Projek Slim dengan ServBay
Panduan ini menggunakan persekitaran PHP pra-dipasang dalam ServBay serta fungsi Websites untuk mengkonfigurasi pelayan web dan akses ke projek Slim anda.
Syarat Awal
Sebelum bermula, pastikan perkara berikut telah dipenuhi:
- Pemasangan & ServBay Berjalan: ServBay sudah dipasang dengan betul di sistem macOS atau Windows anda, dan aplikasi ServBay sedang berjalan.
- Composer Disediakan: ServBay didatangkan dengan Composer, jadi anda tidak perlu pemasangan berasingan.
Membina Projek Slim
Adalah disarankan supaya semua projek web disimpan dalam folder tertentu supaya ServBay dapat menguruskannya dengan efektif:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
Langkah-langkah:
Akses folder root ServBay:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1Cipta folder projek: Buat folder baharu untuk projek Slim anda.
bashmkdir servbay-slim-app
1Masuk ke folder projek:
bashcd servbay-slim-app
1Pasang Slim Framework dengan Composer: Jalankan Composer untuk pasang Slim dan implementasi PSR-7.
bashcomposer require slim/slim "^4.0" slim/psr7 -W
1Arahan ini akan memuat turun Slim dan pustaka
slim/psr7
ke dalam foldervendor
, serta menghasilkan failcomposer.json
dancomposer.lock
.
Inisialisasi Aplikasi Slim
- Cipta fail entry: Aplikasi Slim biasanya bermula dengan satu entry file (contoh:
public/index.php
). Buat folderpublic
dalam root projek dan failindex.php
di dalamnya.bashmkdir public touch public/index.php
1
2 - Edit fail entry: Buka
public/index.php
dan masukkan kod berikut:phpKod di atas mencipta aplikasi Slim paling asas: laluan GET ke URL root (<?php // Muatkan fail autoload Composer require __DIR__ . '/../vendor/autoload.php'; // Import interface PSR-7 dan kelas Slim Factory use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; // Inisialisasi aplikasi Slim $app = AppFactory::create(); // Tambah route asas: layan permintaan GET ke '/' $app->get('/', function (Request $request, Response $response, $args) { // Tulis teks ke response body $response->getBody()->write("Hello ServBay!"); // Kembalikan 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/
) akan mengembalikan teks "Hello ServBay!" sebagai respons.
Konfigurasi Website di ServBay
Untuk mengakses projek Slim dari browser, anda perlu konfigurasi Website (atau "Host" dalam versi lama) di ServBay.
- Buka antaramuka aplikasi ServBay.
- Navigasi ke modul Websites.
- Klik "Tambah Website Baru".
- Isi maklumat:
Name:
My First Slim Dev Site
(atau nama pilihan anda)Domain:
servbay-slim-test.local
(Disarankan gunakan suffix.local
atau.test
untuk pembangunan tempatan)Website Type:
PHP
PHP Version: Pilih versi PHP yang diperlukan, contoh
8.3
.Document Root: Klik "Browse" dan pilih folder
public
dalam projek:- macOS:
/Applications/ServBay/www/servbay-slim-app/public
- Windows:
C:\ServBay\www\servbay-slim-app\public
Ini kerana fail entry
index.php
Slim terletak di dalam folderpublic
, jadi server perlu menghala permintaan ke folder ini.- macOS:
- Simpan konfigurasi website. ServBay akan kemaskini dan aktifkan tetapan pelayan web secara automatik.
Untuk langkah terperinci, rujuk Menambah Website Pertama.
Mengakses Website Slim Anda
Setelah konfigurasi selesai, buka pelayar web dan lawati domain yang telah ditetapkan: https://servbay-slim-test.local
.
Jika semuanya berjalan lancar, anda akan melihat teks Hello ServBay!
di paparan browser – menandakan projek Slim telah berjalan dengan jayanya melalui ServBay.
Contoh Integrasi Pangkalan Data
Slim sendiri tidak menyediakan lapisan pengabstrakan database, tetapi boleh digabung dengan pelbagai pustaka PHP berkaitan database. Dalam contoh ini, kami guna Eloquent ORM Laravel (melalui komponen illuminate/database
) untuk sambungan MySQL dan PostgreSQL, serta contoh integrasi Memcached dan Redis.
Syarat Awal: Cipta Database & Jalankan Migration
Sebelum integrasi database, cipta database baru dalam ServBay serta struktur jadual yang diperlukan untuk aplikasi anda.
- Cipta database:
- Buka aplikasi ServBay, navigasi ke pakej database yang digunakan (MySQL atau PostgreSQL).
- Guna alat pengurusan seperti phpMyAdmin untuk MySQL/MariaDB, pgAdmin untuk PostgreSQL, ataupun klien baris arahan – untuk cipta database baru, contoh dinamakan
servbay_slim_app
. - Kata laluan root database ServBay biasanya
password
, tapi boleh disemak atau diubah melalui antaramuka ServBay.
- Pasang & konfigurasi Phinx (alat migration): Phinx digunakan untuk urus migrasi struktur database.
- Dari root projek Slim anda:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require robmorgan/phinx
1 - macOS:
- Inisialisasi Phinx:bashIni akan hasilkan fail konfigurasi
vendor/bin/phinx init
1phinx.yml
. Edit dan masukkan sambungan database anda, contohnya:yamlpaths: migrations: '%%PHINX_CONFIG_DIR%%/db/migrations' seeds: '%%PHINX_CONFIG_DIR%%/db/seeds' environments: default_migration_table: phinxlog default_environment: development development: adapter: mysql # atau pgsql host: 127.0.0.1 name: servbay_slim_app user: root pass: password port: 3306 # MySQL default, PostgreSQL 5432 charset: utf8mb4 collation: utf8mb4_unicode_ci version_order: creation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- Dari root projek Slim anda:
- Cipta fail migrasi: Guna Phinx untuk hasilkan fail migrasi baru.bashFail PHP baru akan muncul dalam folder
vendor/bin/phinx create CreateUsersTable
1db/migrations
. Edit metodechange()
untuk tentukan schema jadualusers
:php<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateUsersTable extends AbstractMigration { /** * Change Method. * * Tulis migrasi yang boleh balik guna kaedah ini. * * Maklumat lanjut: https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method * * Ingat untuk gunakan "create()" atau "update()", bukan "save()" bila guna kelas Table. */ public function change(): void { $table = $this->table('users'); $table->addColumn('name', 'string') ->addColumn('email', 'string', ['unique' => true]) ->addTimestamps() // Menambah medan 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 - Jalankan migration: Di root projek, jalankan migration supaya jadual
users
diwujudkan.bashPenting: Selesaikan ciptaan database & migrasi sebelum menjalankan kod contoh database di bawah.vendor/bin/phinx migrate
1
Guna Komponen illuminate/database
Kita akan gunakan komponen database Laravel (illuminate/database
) sebagai ORM/query builder.
Pasang illuminate/database: Dari root projek:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require illuminate/database
1- macOS:
Konfigurasi sambungan database dalam
public/index.php
: Tambah kod konfigurasi tepat selepasrequire __DIR__ . '/../vendor/autoload.php';
dan sebelum$app = AppFactory::create();
.php// ... require & use lain ... use Illuminate\Database\Capsule\Manager as Capsule; // Import Capsule // Inisialisasi Eloquent ORM $capsule = new Capsule; // Tambah konfigurasi connection (ubah driver/db info ikut keperluan) $capsule->addConnection([ 'driver' => 'mysql', // atau 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', // Untuk PostgreSQL tambah: 'schema' => 'public', ]); // Buat global $capsule->setAsGlobal(); // Mulakan Eloquent $capsule->bootEloquent(); // ... cipta aplikasi 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
Contoh MySQL
Anggap anda sudah cipta database MySQL servbay_slim_app
dan jadual users
via migration.
Tambah route baharu ke dalam public/index.php
, sebelum $app->run();
:
php
// ... kod sebelum ini & route '/'
use Illuminate\Database\Capsule\Manager as Capsule; // Pastikan telah diimport
// Route tambah data pengguna
$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', // Pastikan 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);
}
return $response;
});
// Route ambil data pengguna
$app->get('/mysql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson()); // Output sebagai JSON
$response = $response->withHeader('Content-Type', 'application/json');
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... jalankan aplikasi Slim
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
Cara akses:
- Kunjungi
https://servbay-slim-test.local/mysql-add-user
untuk tambah pengguna ke jadualusers
. - Kunjungi
https://servbay-slim-test.local/mysql-get-users
untuk ambil semua pengguna dalam format JSON.
Contoh PostgreSQL
Jika anda menggunakan PostgreSQL dan telah sediakan database serta jadual seperti sebelumnya (pastikan adapter
Phinx dan port diset ke pgsql
dan 5432
).
Ubah konfigurasi database di public/index.php
, tukar driver
ke pgsql
dan tambah parameter schema
:
php
$capsule->addConnection([
'driver' => 'pgsql',
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
]);
// ... Eloquent Setting lain sama ...
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Tambah route baru sebelum $app->run();
:
php
// ... kod, route sebelumnya ...
// ... route MySQL jika diperlukan ...
use Illuminate\Database\Capsule\Manager as Capsule; // Pastikan telah diimport
// Route tambah pengguna
$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',
'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 ambil pengguna
$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;
});
// ... jalankan aplikasi Slim
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
Cara akses:
- Kunjungi
https://servbay-slim-test.local/pgsql-add-user
untuk tambah pengguna ke jadual PostgreSQL. - Kunjungi
https://servbay-slim-test.local/pgsql-get-users
untuk ambil semua pengguna dalam format JSON.
Contoh Memcached
ServBay menyediakan pakej Memcached dan extension PHP ext-memcached
. Anda hanya perlu pasang pustaka klien PHP, contohnya memcached/memcached
.
Pasang pustaka klien Memcached: Dari root projek:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require memcached/memcached
1- macOS:
Tambah route Memcached dalam
public/index.php
: Sebelum$app->run();
, tambah kod berikut:php// ... kod sebelumnya & database route ... // Memcached route $app->get('/memcached-example', function (Request $request, Response $response, $args) { // Inisialisasi klien Memcached $memcached = new Memcached(); // Sambung ke pelayan Memcached pada 127.0.0.1:11211 $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_servbay_cache_key'; // Cuba ambil data dari cache $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { // Jika tiada, hasilkan data baru dan simpan dalam cache $cachedData = 'Hello Memcached from ServBay! This was not cached.'; $memcached->set($cacheKey, $cachedData, 60); // TTL 60 saat $response->getBody()->write($cachedData); } else { // Data dalam cache – terus digunakan $response->getBody()->write('Hello Memcached from ServBay! This was served from cache.'); } return $response; }); // ... jalankan aplikasi Slim ...
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
Cara akses: Lawati https://servbay-slim-test.local/memcached-example
. kali pertama akan paparkan "This was not cached", akses berikutnya (selagi cache belum tamat tempoh) akan paparkan "This was served from cache".
Contoh Redis
ServBay menyediakan pakej Redis dan extension PHP ext-redis
. Anda perlu pasang klien PHP seperti predis/predis
.
Pasang klien Redis: Dari root projek:
- macOS:
/Applications/ServBay/www/servbay-slim-app
- Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require predis/predis
1- macOS:
Tambah route Redis dalam
public/index.php
: Sebelum$app->run();
, tambah kod berikut:php// ... kod sebelumnya & route database ... // ... route Memcached jika ada ... use Predis\Client as RedisClient; // Import kelas Predis // Redis route $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // Inisialisasi klien Redis pada 127.0.0.1:6379 $redis = new RedisClient([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_servbay_redis_cache_key'; // Cuba ambil data dari cache $cachedData = $redis->get($cacheKey); if ($cachedData === null) { // Jika tiada, hasilkan data baru dan simpan dalam Redis $cachedData = 'Hello Redis from ServBay! This was not cached.'; $redis->setex($cacheKey, 60, $cachedData); // TTL 60 saat $response->getBody()->write($cachedData); } else { // Data dalam cache – terus digunakan $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // Tangkap exception sambungan atau operasi Redis $response->getBody()->write('Error connecting to Redis or performing operation: ' . $e->getMessage()); $response = $response->withStatus(500); } return $response; }); // ... jalankan aplikasi Slim ...
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
Cara akses: Lawati https://servbay-slim-test.local/redis-example
. Kali pertama akan paparkan "This was not cached", akses berikutnya (cache belum tamat tempoh) akan paparkan "This was served from cache".
Rumusan
Melalui langkah di atas, anda telah berjaya membina projek Slim Framework sepenuhnya dalam persekitaran ServBay dan mengkonfigurasi fungsi Websites untuk menghos dan akses projek tersebut. Anda juga belajar cara mengintegrasi pelbagai pakej database seperti MySQL, PostgreSQL, Memcached, Redis berserta extension PHP yang berkaitan untuk membangunkan aplikasi Slim yang berfungsi penuh. ServBay memudahkan pembinaan serta pengurusan environment tempatan agar anda boleh fokus kepada pembangunan aplikasi Slim tanpa gangguan.