สร้างและรันโปรเจกต์ Slim ใน ServBay
บทความนี้จะสอนวิธีสร้าง, ตั้งค่า และใช้งานโปรเจกต์ Slim Framework ด้วย PHP รวดเร็วใน ServBay—แพลตฟอร์มสำหรับเว็บดีเวลลอปบนเครื่องที่ทรงพลังและใช้งานง่าย ServBay มี PHP, เว็บเซิร์ฟเวอร์ (Caddy/Nginx/Apache) และกลุ่มซอฟต์แวร์ฐานข้อมูลที่ครบครัน เหมาะสำหรับการพัฒนา Slim Framework โดยเฉพาะ
Slim คืออะไร?
Slim คือ PHP micro-framework ขนาดเบา ที่ออกแบบมาเพื่อสร้างเว็บแอปหรือ API อย่างง่ายแต่มีประสิทธิภาพสูง รองรับฟีเจอร์หลักเรื่อง routing, จัดการ request/response เหมาะสำหรับงานที่ต้องการพัฒนาและ deploy อย่างรวดเร็ว หรือจะนำไปต่อยอดสร้างระบบขนาดใหญ่ก็ทำได้
จุดเด่นและข้อดีของ Slim
- ขนาดเล็ก: Core ของ Slim มีโค้ดเบา ใช้ทรัพยากรน้อย เริ่มต้นเร็ว เหมาะกับโปรเจกต์ขนาดเล็กหรือบริการแยกส่วน
- ยืดหยุ่นสูง: ออกแบบให้เชื่อมต่อกับไลบรารีและคอมโพเนนท์อื่นๆ ได้ง่าย (เช่น template engine, ORM, authentication ฯลฯ) คุณสามารถเลือกใช้เทคโนโลยีที่เหมาะสมกับโปรเจกต์ของคุณ
- ใช้งานง่าย: API เรียบง่าย พร้อมเอกสารชัดเจน นักพัฒนาจะเข้าใจแนวคิดและเริ่มสร้างระบบได้โดยเร็ว
- Routing ทรงพลัง: รองรับ HTTP methods แบบครบถ้วน (GET, POST, PUT, DELETE ฯลฯ) และตั้งค่า routing ซับซ้อนได้ เช่นจัดกลุ่ม, ใช้งาน middleware, รองรับ route parameters
- Middleware รองรับ: องค์ประกอบ middleware ของ Slim ช่วยให้ตรวจสอบสิทธิ์, log, จัดการ CORS และอื่นๆ ก่อนเข้า logic app หรือก่อนส่ง response
Slim จึงเหมาะมากสำหรับ API แบบ RESTful, การพัฒนา Prototype ไปจนถึงระบบฟีเจอร์เดี่ยว
สร้างและรันโปรเจกต์ Slim ด้วย ServBay
ในคู่มือนี้จะใช้ PHP environment ที่ ServBay ตั้งค่ามาให้ล่วงหน้า บวกกับฟีเจอร์ เว็บไซต์ เพื่อวางเว็บเซิร์ฟเวอร์สำหรับ Slim
ข้อกำหนดเบื้องต้น
ก่อนเริ่ม ขั้นตอนเตรียมความพร้อมมีดังนี้:
- ติดตั้งและเปิด ServBay: ตรวจสอบให้แน่ใจว่า ServBay ถูกติดตั้งและเปิดอยู่บน macOS หรือ Windows
- มี Composer ใน ServBay: ServBay ติดตั้ง Composer มาให้แล้ว ไม่ต้องลงเพิ่ม
สร้างโปรเจกต์ Slim
ServBay แนะนำให้จัดเก็บโปรเจกต์ทั้งหมดไว้ที่:
- macOS:
/Applications/ServBay/www - Windows:
C:\ServBay\www
เข้าสู่โฟลเดอร์หลักของเว็บไซต์ใน ServBay:
macOS:
bashcd /Applications/ServBay/www1Windows:
cmdcd C:\ServBay\www1สร้างโฟลเดอร์โปรเจกต์: ใช้ชื่อใหม่กับ folder สำหรับโปรเจกต์ Slim
bashmkdir servbay-slim-app1เข้า folder โปรเจกต์:
bashcd servbay-slim-app1ติดตั้ง Slim ด้วย Composer: รัน composer ในโฟลเดอร์โปรเจกต์เพื่อติดตั้ง Slim และ PSR-7
bashcomposer require slim/slim "^4.0" slim/psr7 -W1คำสั่งนี้จะดาวน์โหลด Slim และ
slim/psr7มาไว้ในvendorพร้อมสร้างcomposer.jsonและcomposer.lock
ตั้งค่าแอปพลิเคชัน Slim
สร้างไฟล์เริ่มต้นโปรเจกต์: ส่วนมาก Slim จะใช้ไฟล์เดียวเป็น entry point เช่น
public/index.phpสร้างโฟลเดอร์publicและ index.php ในโปรเจกต์bashmkdir public touch public/index.php1
2แก้ไขไฟล์ entry point: เปิด
public/index.phpแล้ววางโค้ดเบื้องต้นของ Slimphp<?php // โหลด Composer autoload require __DIR__ . '/../vendor/autoload.php'; // ใช้ PSR-7 interface และ Slim factory use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; // สร้างแอป Slim $app = AppFactory::create(); // กำหนด route พื้นฐาน: รับ GET ที่ path '/' $app->get('/', function (Request $request, Response $response, $args) { // เขียนข้อความลง response body $response->getBody()->write("Hello ServBay!"); // ส่ง Response กลับ return $response; }); // รันแอป 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โค้ดนี้จะสร้าง Slim app ง่ายๆ ซึ่งเมื่อรับ GET ที่
/จะตอบ “Hello ServBay!”
ตั้งค่าเว็บไซต์ใน ServBay
หากต้องการเข้าเว็บจาก browser ต้องตั้งค่า เว็บไซต์ ใน ServBay (ชื่อเก่าในบางเวอร์ชั่นเรียก “โฮสต์”)
- เปิดหน้าต่างแอพ ServBay
- ไปที่โมดูล เว็บไซต์ (Websites)
- กดเพิ่มเว็บไซต์ใหม่
- กรอกข้อมูลสำหรับโปรเจกต์ของคุณ:
ชื่อ (Name):
My First Slim Dev Site(หรือชื่อใดก็ได้)โดเมน (Domain):
servbay-slim-test.local(ขอแนะนำ .local หรือ .test สำหรับ dev)ชนิดเว็บไซต์ (Website Type):
PHPเวอร์ชั่น PHP (PHP Version): เลือก PHP version ที่ต้องการ เช่น
8.3โฟลเดอร์เว็บไซต์ (Document Root): เลือก
publicโฟลเดอร์ของโปรเจกต์:- macOS:
/Applications/ServBay/www/servbay-slim-app/public - Windows:
C:\ServBay\www\servbay-slim-app\public
เนื่องจากไฟล์ entry ของ Slim คือ
index.phpที่อยู่ในpublicโฟลเดอร์ เว็บเซิร์ฟเวอร์ต้องชี้ไปโฟลเดอร์นี้- macOS:
- บันทึกการตั้งค่า เว็บไซต์ใหม่จะพร้อมใช้งานทันที
ดูขั้นตอนละเอียดได้ที่ การเพิ่มเว็บไซต์แรก
เข้าชมเว็บไซต์ Slim
หลังตั้งค่าเว็บแล้ว เปิดเบราว์เซอร์ พิมพ์โดเมนที่ตั้งไว้ https://servbay-slim-test.local
หากทุกอย่างถูกต้อง คุณจะเห็นหน้าแสดงคำว่า Hello ServBay! นั่นหมายถึงโปรเจกต์ Slim ของคุณเริ่มทำงานผ่านเซิร์ฟเวอร์ ServBay แล้ว
ตัวอย่างการเชื่อมต่อฐานข้อมูล
Slim ไม่มี data abstraction ในตัว แต่เชื่อมกับไลบรารีฐานข้อมูล PHP ได้ง่าย ที่นี่จะยกตัวอย่างการใช้ Eloquent ORM (จาก Laravel ผ่าน illuminate/database) กับ MySQL และ PostgreSQL พร้อมตัวอย่าง Memcached และ Redis
ก่อนเริ่ม: สร้างฐานข้อมูลและ migration
ก่อนเชื่อมฐานข้อมูล ต้องสร้าง db และโครงสร้างตารางของแอปก่อน
สร้างฐานข้อมูล:
- เปิด ServBay แล้วไปที่โมดูล ซอฟต์แวร์ฐานข้อมูล เช่น MySQL หรือ PostgreSQL
- ใช้เครื่องมือที่มาพร้อม เช่น phpMyAdmin (สำหรับ MySQL/MariaDB) หรือ pgAdmin (สำหรับ PostgreSQL) หรือใช้ CLI สร้างฐานข้อมูลใหม่ เช่น
servbay_slim_app - รหัสผ่าน root เริ่มต้นของฐานข้อมูล ServBay โดยมากคือ
password(เปลี่ยน/ดูได้ในหน้า ServBay)
ติดตั้งและตั้งค่า Phinx (migration tool): Phinx ใช้จัดการ version ของโครงสร้างฐานข้อมูล
- ติดตั้ง Phinx ด้วย Composer ที่ root โปรเจกต์:
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require robmorgan/phinx1 - macOS:
- ตั้งค่าเริ่มต้น Phinx:bashจะสร้างไฟล์
vendor/bin/phinx init1phinx.ymlกำหนดค่าการเชื่อมต่อ db ตัวอย่าง:yamlpaths: migrations: '%%PHINX_CONFIG_DIR%%/db/migrations' seeds: '%%PHINX_CONFIG_DIR%%/db/seeds' environments: default_migration_table: phinxlog default_environment: development # หรือชื่อ environment ที่ตั้งไว้ development: # เปลี่ยนตามประเภท db adapter: mysql # หรือ pgsql host: 127.0.0.1 name: servbay_slim_app # ชื่อฐานข้อมูล user: root pass: password # รหัสผ่านฐานข้อมูล port: 3306 # Port MySQL, PostgreSQL คือ 5432 charset: utf8mb4 # แนะนำ MySQL collation: utf8mb4_unicode_ci # แนะนำ MySQL version_order: creation1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- ติดตั้ง Phinx ด้วย Composer ที่ root โปรเจกต์:
สร้าง migration file: ใช้คำสั่ง Phinx เพื่อสร้างไฟล์ migration ใหม่
bashvendor/bin/phinx create CreateUsersTable1ผลลัพธ์จะออกไฟล์ PHP ใน
db/migrationsเปิดไฟล์นั้นแล้วกำหนดว่าuserstable มีอะไรบ้าง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() // เพิ่มฟิลด์ created_at และ 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รัน migration: ที่ root โปรเจกต์ ใช้คำสั่งด้านล่างเพื่อสร้าง
userstablebashvendor/bin/phinx migrate1สำคัญ: ต้องสร้างฐานข้อมูลและ run migration จนครบก่อนค่อยทดสอบตัวอย่างฐานข้อมูลข้างล่าง
ใช้งาน illuminate/database
จะใช้คอมโพเนนท์ database จาก Laravel (illuminate/database)
ติดตั้ง illuminate/database: ติดตั้งผ่าน Composer ที่ root โปรเจกต์
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require illuminate/database1- macOS:
เพิ่มโค้ดเชื่อมต่อฐานข้อมูลใน
public/index.phpใส่หลังrequire __DIR__ . '/../vendor/autoload.php';แต่ก่อนสร้าง$app = AppFactory::create();เช่น:php// ... require และ use ที่จำเป็น ... use Illuminate\Database\Capsule\Manager as Capsule; // ใช้งาน Capsule // เริ่มต้น Eloquent ORM $capsule = new Capsule; // กำหนดค่าการเชื่อมต่อ db (แก้ driver/parameter ตาม db ที่ใช้) $capsule->addConnection([ 'driver' => 'mysql', // หรือ 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', // ชื่อฐานข้อมูล 'username' => 'root', // ชื่อผู้ใช้ฐานข้อมูล 'password' => 'password', // รหัสผ่าน 'charset' => 'utf8mb4', // แนะนำ MySQL 'collation' => 'utf8mb4_unicode_ci', // แนะนำ MySQL 'prefix' => '', // สำหรับ PostgreSQL ใส่ schema ด้วย // 'schema' => 'public', ]); // ใช้งาน capsule ทั่วทั้งโปรเจกต์ $capsule->setAsGlobal(); // เปิดใช้ Eloquent ORM $capsule->bootEloquent(); // ... สร้าง Slim app ($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
ตัวอย่าง MySQL
เมื่อเปิดใช้งาน MySQL ซอฟต์แวร์ ใน ServBay แล้ว, สร้างฐานข้อมูล servbay_slim_app และรัน migration เพื่อสร้าง users table
ใน public/index.php เพิ่ม routing ก่อน $app->run(); แบบนี้
php
// ... โค้ดก่อนหน้าและ route '/' ...
use Illuminate\Database\Capsule\Manager as Capsule; // อย่าลืม import
// route สำหรับเพิ่มผู้ใช้
$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', // ใช้ time() สำหรับ email ไม่ซ้ำ
'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 สำหรับดึงข้อมูลผู้ใช้
$app->get('/mysql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson()); // แปลงผลลัพธ์เป็น JSON
$response = $response->withHeader('Content-Type', 'application/json'); // กำหนด 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
การเข้าใช้งาน:
- เข้า
https://servbay-slim-test.local/mysql-add-userเพื่อบันทึกผู้ใช้ใหม่ลง tableusers - เข้า
https://servbay-slim-test.local/mysql-get-usersเพื่อดึงทุกผู้ใช้ในรูปแบบ JSON
ตัวอย่าง PostgreSQL
เช่นเดียวกับ MySQL, เปิดใช้งาน PostgreSQL ซอฟต์แวร์ สร้างฐานข้อมูลและรัน migration ให้สมบูรณ์ (ตรวจสอบว่า phinx ตั้งค่า adapter เป็น pgsql, port เป็น 5432)
แก้ config การเชื่อม db ใน public/index.php (เปลี่ยน driver และเพิ่ม schema):
php
$capsule->addConnection([
'driver' => 'pgsql', // ใช้ pgsql
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8', // PostgreSQL แนะนำ utf8
'prefix' => '',
'schema' => 'public', // กำหนด schema สำหรับ PostgreSQL
]);
// ... ส่วนอื่นของ Eloquent เหมือนเดิม ...1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
เพิ่ม route เหมือนกับฝั่ง MySQL ก่อน $app->run();:
php
// ... โค้ดก่อนหน้าและ route '/'
// ... route MySQL (ถ้าต้องการ) ...
use Illuminate\Database\Capsule\Manager as Capsule; // อย่าลืม import
// route เพิ่มผู้ใช้
$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', // ใช้ time() เพื่อ email ไม่ซ้ำ
'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 ดึงข้อมูลผู้ใช้
$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
การเข้าใช้งาน:
- เข้า
https://servbay-slim-test.local/pgsql-add-userเพื่อเพิ่มผู้ใช้ลง tableusersของ PostgreSQL - เข้า
https://servbay-slim-test.local/pgsql-get-usersเพื่อดึงข้อมูลจาก PostgreSQL ในรูป JSON
ตัวอย่าง Memcached
ServBay ติดตั้ง Memcached ซอฟต์แวร์ และ PHP extension ext-memcached มาให้ เลือกใช้ client PHP ที่ต้องการ ที่นี่จะใช้ memcached/memcached
ติดตั้ง Memcached client: ใช้ Composer ที่ root โปรเจกต์
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require memcached/memcached1- macOS:
เพิ่ม route Memcached ใน
public/index.php: เพิ่มก่อน$app->run();php// ... โค้ดก่อนหน้าและ route ฐานข้อมูล ... // route สำหรับ Memcached $app->get('/memcached-example', function (Request $request, Response $response, $args) { // สร้าง instance ของ Memcached client $memcached = new Memcached(); // เพิ่มเซิร์ฟเวอร์ Memcached (ServBay เริ่มต้นที่ 127.0.0.1:11211) $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_servbay_cache_key'; // พยายามดึงข้อมูลจาก cache $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { // ยังไม่มีข้อมูลใน cache สร้างข้อมูลใหม่และบันทึก $cachedData = 'Hello Memcached from ServBay! This was not cached.'; // บันทึกใน cache อายุ 60 วินาที $memcached->set($cacheKey, $cachedData, 60); $response->getBody()->write($cachedData); } else { // มีข้อมูลใน 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
การเข้าใช้งาน: เยี่ยมชม https://servbay-slim-test.local/memcached-example ครั้งแรกจะแสดง "This was not cached." รอบต่อไป (ก่อนหมดเวลา cache) จะขึ้น "This was served from cache."
ตัวอย่าง Redis
ServBay ก็มาพร้อม Redis ซอฟต์แวร์ และ PHP extension ext-redis ให้ใช้ client PHP ที่ชอบ ที่นี่เลือก predis/predis
ติดตั้ง Redis client: ติดตั้งผ่าน Composer ที่ root โปรเจกต์
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require predis/predis1- macOS:
เพิ่ม route Redis ใน
public/index.php: ใส่ก่อน$app->run();php// ... โค้ดก่อนหน้าและ route ฐานข้อมูล ... // ... route Memcached (ถ้ามี) ... use Predis\Client as RedisClient; // ใช้ Predis client // route สำหรับ Redis $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // สร้าง Redis client (ServBay เริ่มต้นที่ 127.0.0.1:6379) $redis = new RedisClient([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_servbay_redis_cache_key'; // พยายามดึงข้อมูลจาก Redis $cachedData = $redis->get($cacheKey); if ($cachedData === null) { // ยังไม่มีข้อมูลใน cache สร้างข้อมูลใหม่และบันทึก $cachedData = 'Hello Redis from ServBay! This was not cached.'; // บันทึกลง Redis พร้อมกำหนดอายุข้อมูล 60 วินาที $redis->setex($cacheKey, 60, $cachedData); // SETEX key seconds value $response->getBody()->write($cachedData); } else { // มีข้อมูลใน cache ใช้ข้อมูลเดิม $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // ดัก Error การเชื่อมต่อหรืออื่นๆ $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
การเข้าใช้งาน: เยี่ยมชม https://servbay-slim-test.local/redis-example ครั้งแรกจะขึ้นข้อความ "This was not cached." หลังจากนั้น (ก่อนหมดเวลา cache) ขึ้น "This was served from cache."
บทสรุป
จากขั้นตอนข้างต้น คุณจะสามารถสร้างโปรเจกต์ Slim Framework บนสภาพแวดล้อม local ของ ServBay ได้สำเร็จ พร้อมตั้งค่าเว็บ เซิร์ฟเวอร์ และเชื่อมต่อฐานข้อมูลยอดนิยมทั้ง MySQL, PostgreSQL, Memcached, Redis โดยใช้ PHP extension และคอมโพเนนท์ที่สนับสนุน ServBay ทำให้การติดตั้งและจัดการ local dev ง่ายขึ้น คุณก็จะโฟกัสกับการพัฒนาแอป Slim ได้เต็มที่
