Membuat dan Menjalankan Proyek CodeIgniter
Apa itu CodeIgniter?
CodeIgniter adalah framework pengembangan aplikasi web PHP yang ringan dan berkinerja tinggi. Framework ini mengikuti pola desain Model-View-Controller (MVC) dan dirancang untuk membantu developer membangun aplikasi web yang kaya fitur dengan cepat. Dengan struktur yang sederhana, performa yang hebat, dan kemudahan belajar, CodeIgniter menjadi pilihan utama bagi banyak pengembang PHP.
Fitur Utama dan Kelebihan CodeIgniter
- Core Ringan: Sistem inti CodeIgniter sangat minimal, hanya mencakup komponen dasar yang diperlukan untuk menjalankan aplikasi sehingga proses loading sangat cepat.
- Performa Unggul: Framework ini didesain efisien untuk menangani permintaan dengan traffic tinggi dan memberikan performa aplikasi yang luar biasa.
- Mudah Dipelajari: Dokumentasi yang jelas dan API yang intuitif membuat proses pembelajaran lebih mudah, sehingga developer bisa menguasainya dengan cepat.
- Sangat Fleksibel: Developer bebas memilih dan mengintegrasikan library pihak ketiga sesuai kebutuhan proyek, memungkinkan penyesuaian dan pengembangan fitur secara optimal.
- Komunitas Aktif: Didukung oleh komunitas pengembang yang besar dan aktif, sehingga tersedia banyak sumber daya dan dukungan.
CodeIgniter ideal untuk kebutuhan pengembangan mulai dari proyek kecil hingga aplikasi skala enterprise, membantu developer menghasilkan solusi web berkualitas tinggi secara efisien.
Menyiapkan Lingkungan Pengembangan CodeIgniter dengan ServBay
ServBay adalah alat lingkungan pengembangan web lokal untuk macOS dan Windows yang telah terintegrasi dengan PHP, database (MySQL, PostgreSQL, MongoDB), cache (Redis, Memcached), dan web server (Caddy, Nginx, Apache), serta dilengkapi dengan antarmuka manajemen yang mudah digunakan. Dengan ServBay, Anda dapat menyiapkan dan mengelola lingkungan pengembangan CodeIgniter dengan mudah.
Panduan ini akan membantu Anda memanfaatkan lingkungan PHP dan fitur website ServBay untuk membuat, mengonfigurasi, dan menjalankan proyek CodeIgniter, serta mendemonstrasikan cara mengintegrasikan berbagai service database dan cache.
Persyaratan Awal
Sebelum memulai, pastikan Anda telah menyiapkan:
- ServBay sudah terinstal dan berjalan di macOS atau Windows.
- Versi PHP yang hendak digunakan sudah diaktifkan di ServBay (misal, PHP 8.3).
- Paket database dan cache yang akan digunakan (misal, MySQL, PostgreSQL, Redis, Memcached) sudah diaktifkan di ServBay.
Membuat Proyek CodeIgniter
ServBay menyarankan Anda menyimpan proyek website Anda di direktori berikut agar pengelolaan lebih mudah:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
Instal Composer
ServBay telah menyediakan Composer secara built-in, jadi Anda biasanya tidak perlu menginstallnya secara manual. Anda dapat langsung menggunakan perintah
composer
di terminal.Masuk ke Direktori Root Website
Buka terminal dan masuk ke direktori root website yang direkomendasikan ServBay:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1Membuat Proyek CodeIgniter
Gunakan Composer untuk membuat proyek CodeIgniter 4 baru. Misal, nama direktori proyek:
servbay-codeigniter-app
:bashcomposer create-project codeigniter4/appstarter servbay-codeigniter-app
1Composer akan mengunduh struktur aplikasi CodeIgniter dan dependensi ke dalam folder
servbay-codeigniter-app
.Masuk ke Direktori Proyek
Masuk ke folder proyek CodeIgniter yang baru dibuat:
macOS:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Windows:
cmdcd C:\ServBay\www\servbay-codeigniter-app
1
Inisialisasi Konfigurasi
Konfigurasi Koneksi Database
Konfigurasi database CodeIgniter terletak di file app/Config/Database.php
. Anda perlu mengatur detail koneksi database di file ini sebelum menggunakan database.
Pertama, jika Anda ingin memakai database, pastikan Anda sudah membuat database bernama servbay_codeigniter_app
melalui tool manajemen database ServBay (seperti Adminer atau phpMyAdmin yang tersedia pada antarmuka aplikasi ServBay).
Selanjutnya, edit file app/Config/Database.php
, lalu temukan array $default
dan isi informasi koneksi sesuai tipe database yang diaktifkan di ServBay (misal, MySQL atau PostgreSQL). Username dan password database ServBay biasanya adalah root
dan password
.
Contoh konfigurasi MySQL:
php
public $default = [
'DSN' => '',
'hostname' => '127.0.0.1', // Database ServBay biasanya berjalan di 127.0.0.1
'username' => 'root', // Username default ServBay
'password' => 'password', // Password default ServBay
'database' => 'servbay_codeigniter_app', // Nama database yang Anda buat
'DBDriver' => 'MySQLi', // Pilih driver sesuai tipe database, MySQL pakai MySQLi atau Pdo
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306, // Port default MySQL
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Jika Anda menggunakan PostgreSQL, set DBDriver
ke 'Postgre'
, biasanya port adalah 5432
, dan pengaturan charset mungkin perlu disesuaikan.
Konfigurasi Koneksi Cache (Memcached/Redis)
Untuk menggunakan Memcached atau Redis sebagai cache, Anda perlu mengatur koneksi pada file app/Config/Cache.php
.
Edit file app/Config/Cache.php
dan sesuaikan pengaturan pada bagian yang relevan. Default port Memcached di ServBay adalah 11211
dan Redis adalah 6379
, biasanya tanpa password.
Contoh konfigurasi Memcached:
php
public $memcached = [
'host' => '127.0.0.1', // Memcached ServBay biasanya berjalan di 127.0.0.1
'port' => 11211, // Port default Memcached
'weight' => 1,
];
1
2
3
4
5
2
3
4
5
Contoh konfigurasi Redis:
php
public string $handler = 'redis'; // Menetapkan handler cache default ke redis
public $default = [ // Pengaturan Redis biasanya ada di array default
'host' => '127.0.0.1', // Redis ServBay berjalan di 127.0.0.1
'password' => null, // Redis ServBay biasanya tanpa password
'port' => 6379, // Port default Redis
'timeout' => 0,
'database' => 0,
];
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Pastikan Anda mengatur konfigurasi pada bagian yang sesuai dengan paket cache yang Anda aktifkan.
Konfigurasi Web Server (Pengaturan Website ServBay)
Gunakan fitur website ServBay untuk mengonfigurasi web server sehingga mengarah ke proyek CodeIgniter Anda.
- Buka antarmuka aplikasi ServBay.
- Navigasi ke tab Websites.
- Klik tombol
+
di pojok kiri bawah untuk menambah website baru. - Isi informasi website:
- Nama (Name): Masukkan nama yang mudah dikenali, misal
My First CodeIgniter Dev Site
. - Domain (Domain): Masukkan domain yang ingin Anda akses di browser local, misal
servbay-codeigniter-test.local
. ServBay akan otomatis mengarahkan domain.local
ke komputer Anda. - Tipe Website (Site Type): Pilih
PHP
. - Versi PHP (PHP Version): Pilih versi PHP yang Anda inginkan, misal
8.3
. - Root Website (Document Root): Ini langkah penting. File entry CodeIgniter (
index.php
) ada di folderpublic
pada direktori proyek. Jadi, root website harus disetel ke folderpublic
di dalam folder proyek:/Applications/ServBay/www/servbay-codeigniter-app/public
.
- Nama (Name): Masukkan nama yang mudah dikenali, misal
- Klik Add untuk menyimpan pengaturan.
- ServBay mungkin akan meminta Anda menerapkan perubahan, klik konfirmasi.
Instruksi lebih detail dapat Anda lihat di Menambah Website Pertama.
Menambah Kode Contoh
Untuk memverifikasi apakah proyek Anda berjalan normal dan menguji koneksi database serta cache, kita akan memodifikasi controller default CodeIgniter, yaitu Home
, dan menambahkan beberapa metode contoh.
Edit file app/Controllers/Home.php
dan ganti isinya dengan kode berikut:
php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\Database\Exceptions\DatabaseException; // Import kelas exception database
use CodeIgniter\Cache\Exceptions\CacheException; // Import kelas exception cache
class Home extends Controller
{
/**
* Metode halaman utama default
*/
public function index(): string
{
// Tampilkan pesan sambutan sederhana
return '<h1>Hello ServBay and CodeIgniter!</h1><p>Your CodeIgniter project is running on ServBay.</p>';
}
/**
* Metode contoh Memcached
*/
public function memcached(): string
{
try {
$cache = \Config\Services::cache();
// Mencoba menyimpan ke cache
$success = $cache->save('servbay_memcached_key', 'Hello Memcached from CodeIgniter!', 60); // Cache 60 detik
if (!$success) {
return 'Error: Failed to save data to Memcached. Check Memcached service and configuration.';
}
// Mencoba membaca dari cache
$value = $cache->get('servbay_memcached_key');
if ($value === null) {
return 'Error: Failed to get data from Memcached. Cache might have expired or service is down.';
}
return 'Memcached Test Success: ' . $value;
} catch (CacheException $e) {
// Tangkap exception terkait cache
return 'Cache Error: ' . $e->getMessage() . '. Ensure Memcached service is running and configured correctly.';
} catch (\Exception $e) {
// Tangkap exception lainnya
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Metode contoh Redis
*/
public function redis(): string
{
try {
$cache = \Config\Services::cache();
// Mencoba menyimpan ke cache
$success = $cache->save('servbay_redis_key', 'Hello Redis from CodeIgniter!', 60); // Cache 60 detik
if (!$success) {
return 'Error: Failed to save data to Redis. Check Redis service and configuration.';
}
// Mencoba membaca dari cache
$value = $cache->get('servbay_redis_key');
if ($value === null) {
return 'Error: Failed to get data from Redis. Cache might have expired or service is down.';
}
return 'Redis Test Success: ' . $value;
} catch (CacheException $e) {
// Tangkap exception terkait cache
return 'Cache Error: ' . $e->getMessage() . '. Ensure Redis service is running and configured correctly.';
} catch (\Exception $e) {
// Tangkap exception lainnya
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Menyimpan data user ke database (MySQL/PostgreSQL)
*/
public function addUser(): string
{
try {
$db = \Config\Database::connect();
// Cek apakah tabel 'users' ada (langkah pencegahan)
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// Insert data
$data = [
'name' => 'ServBay Demo User',
'email' => 'user_' . time() . '@servbay.demo', // Buat email unik pakai time()
];
$db->table('users')->insert($data);
// Cek apakah insert berhasil (opsional, insert() umumnya return true)
// if ($db->affectedRows() > 0) {
return 'User added successfully: ' . $data['email'];
// } else {
// return 'Error: Failed to add user.';
// }
} catch (DatabaseException $e) {
// Tangkap exception database
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Tangkap exception lainnya
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Membaca data user dari database (MySQL/PostgreSQL)
*/
public function listUsers(): string
{
try {
$db = \Config\Database::connect();
// Cek apakah tabel 'users' ada
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// Query semua user
$users = $db->table('users')->get()->getResult();
if (empty($users)) {
return 'No users found in the database.';
}
// Kembalikan data user dalam format JSON
return json_encode($users);
} catch (DatabaseException $e) {
// Tangkap exception database
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Tangkap exception lainnya
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
}
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
Controller yang sudah dimodifikasi ini memiliki output yang jelas dan penanganan error dasar untuk membantu proses diagnosa masalah.
Konfigurasi Routing
Supaya bisa mengakses metode contoh pada controller Home
lewat URL, tambahkan aturan routing di file routing CodeIgniter.
Edit file app/Config/Routes.php
. Cari bagian definisi $routes
, lalu tambahkan baris berikut:
php
// ... aturan routing lain ...
// Routing contoh Memcached
$routes->get('/memcached', 'Home::memcached');
// Routing contoh Redis
$routes->get('/redis', 'Home::redis');
// Routing contoh database
$routes->get('/add-user', 'Home::addUser');
$routes->get('/list-users', 'Home::listUsers');
// ... aturan routing lain ...
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Pastikan Anda menambah rute baru ini pada array $routes
yang sudah ada, jangan menimpa rute yang sudah ada sebelumnya.
Mengakses Website
Kini proyek CodeIgniter Anda sudah berjalan di ServBay. Buka browser, dan akses dengan domain yang sudah Anda atur:
Akses halaman utama:
https://servbay-codeigniter-test.local
Anda seharusnya melihat halaman bertuliskanHello ServBay and CodeIgniter!
, menandakan project Anda berjalan lancar dengan web server ServBay.Akses contoh Memcached:
https://servbay-codeigniter-test.local/memcached
Jika layanan Memcached sudah berjalan dan konfigurasi benar, Anda akan melihat output sepertiMemcached Test Success: Hello Memcached from CodeIgniter!
.Akses contoh Redis:
https://servbay-codeigniter-test.local/redis
Jika layanan Redis sudah berjalan dan konfigurasi benar, Anda akan melihat output sepertiRedis Test Success: Hello Redis from CodeIgniter!
.
Contoh Operasi Database (MySQL/PostgreSQL)
Sebelum menjalankan contoh operasi database, Anda perlu menjalankan perintah migrasi CodeIgniter untuk membuat tabel users
.
Membuat Struktur Database (Menjalankan Migrasi)
Buka terminal dan masuk ke direktori proyek CodeIgniter:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Buat file migrasi: Gunakan CLI CodeIgniter untuk menghasilkan file migrasi yang mendefinisikan struktur tabel
users
:bashphp spark make:migration create_users_table
1File migrasi baru akan muncul pada folder
app/Database/Migrations
.Edit file migrasi: Buka file baru (default namanya seperti
YYYY-MM-DD-HHMMSS_CreateUsersTable.php
), dan edit metodeup()
untuk mendefinisikan kolom dan index tabelusers
. Perhatikan, MySQL dan PostgreSQL punya sedikit perbedaan pada penulisan default value auto-timestamp (CURRENT_TIMESTAMP
vsNOW()
). CodeIgniter menyediakanRawSql
untuk membantu pengaturan ini. Contohnya:php<?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; use CodeIgniter\Database\RawSql; // Pastikan mengimpor RawSql class CreateUsersTable extends Migration { public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true, ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '100', ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => '100', 'unique' => true, // Email harus unik ], 'created_at' => [ 'type' => 'TIMESTAMP', // Pilih default value sesuai tipe database // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP' : 'NOW()'), ], 'updated_at' => [ 'type' => 'TIMESTAMP', // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' : 'NOW()'), ], ]); $this->forge->addKey('id', true); // Set primary key di kolom id $this->forge->createTable('users'); // Buat tabel users } public function down() { // Rollback migrasi, hapus tabel users $this->forge->dropTable('users'); } }
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
41
42
43
44
45
46
47
48
49
50
51Catatan: Pada contoh di atas, default value timestamp dipilih dinamis sesuai platform database. Pada proyek nyata, Anda mungkin perlu strategi migrasi lebih modular, atau migrasi terpisah untuk tiap database.
Menjalankan migrasi: Jalankan perintah berikut di terminal untuk menjalankan migrasi dan membuat tabel
users
:bashphp spark migrate
1Jika migration sukses, Anda akan melihat pesan sukses di terminal. Anda juga bisa cek di tool admin database (misal Adminer) pada database
servbay_codeigniter_app
apakah tabelusers
sudah muncul.
Mengakses Contoh Database
Pastikan Anda telah mengatur koneksi database dengan benar di app/Config/Database.php
dan sudah menjalankan migrasi untuk membuat tabel users
.
Tambah user ke database: Akses
https://servbay-codeigniter-test.local/add-user
Setiap kali mengakses URL ini, data user baru akan ditambah ke tabelusers
. Output akan sepertiUser added successfully: user_XXXXXXXXXX@servbay.demo
.Tampilkan daftar user: Akses
https://servbay-codeigniter-test.local/list-users
URL ini akan menampilkan semua data user di tabelusers
dalam format JSON.
Kesimpulan
Setelah mengikuti langkah-langkah di atas, Anda telah berhasil membuat, mengonfigurasi, dan menjalankan proyek CodeIgniter di lingkungan ServBay pada macOS/Windows. Anda sudah belajar cara membuat proyek dengan Composer, mengatur website ServBay mengarah ke folder yang benar, mengonfigurasi koneksi database dan cache CodeIgniter, serta menguji integrasinya melalui kode contoh sederhana. ServBay membantu menyederhanakan proses setup lingkungan lokal, sehingga Anda bisa lebih fokus ke pengembangan aplikasi CodeIgniter.