Membuat dan Menjalankan Proyek CodeIgniter
Apa Itu CodeIgniter?
CodeIgniter adalah sebuah framework pengembangan aplikasi Web PHP yang ringan dan berperforma tinggi. Framework ini menerapkan pola desain Model-View-Controller (MVC) dan dirancang untuk membantu para pengembang membangun aplikasi web yang kaya fitur dengan cepat. Struktur yang sederhana, performa unggulan, serta kemudahan penggunaannya menjadikan CodeIgniter pilihan utama banyak pengembang PHP.
Fitur Utama dan Keunggulan CodeIgniter
- Inti Ringan: Sistem inti CodeIgniter sangat ramping, hanya memuat komponen dasar yang diperlukan untuk menjalankan aplikasi, sehingga waktu pemuatan menjadi sangat cepat.
- Performa Unggul: Framework ini dirancang untuk efisiensi, mampu menangani permintaan bersamaan dengan baik, dan memberikan performa aplikasi yang luar biasa.
- Mudah Dipelajari: Dokumentasi yang jelas dan API yang intuitif membuat kurva pembelajaran menjadi rendah, sehingga pengembang dapat menguasainya dengan cepat.
- Sangat Fleksibel: Pengembang bebas memilih dan mengintegrasikan pustaka pihak ketiga sesuai kebutuhan proyek, memudahkan ekstensi dan kustomisasi fitur.
- Dukungan Komunitas Aktif: Memiliki komunitas pengembang yang besar dan aktif dengan sumber daya serta dukungan yang melimpah.
CodeIgniter cocok untuk berbagai kebutuhan pengembangan mulai dari proyek kecil hingga aplikasi tingkat enterprise besar, mendukung pengembang untuk membangun solusi web berkualitas secara efisien.
Menyiapkan Lingkungan Pengembangan CodeIgniter dengan ServBay
ServBay adalah alat lingkungan pengembangan web lokal yang dirancang khusus untuk macOS. Aplikasi ini mengintegrasikan PHP, database (MySQL, PostgreSQL, MongoDB), cache (Redis, Memcached), server web (Caddy, Nginx, Apache), dan berbagai paket perangkat lunak lainnya dalam satu antarmuka manajemen yang praktis. Dengan ServBay, Anda dapat dengan mudah menyiapkan dan mengelola lingkungan pengembangan yang dibutuhkan CodeIgniter.
Panduan ini akan memandu Anda menggunakan lingkungan PHP ServBay dan fitur Website untuk membuat, mengkonfigurasi, dan menjalankan proyek CodeIgniter, serta demonstrasi integrasi berbagai layanan database dan cache.
Prasyarat
Sebelum memulai, pastikan Anda telah melakukan hal berikut:
- Sudah menginstall dan menjalankan ServBay dengan sukses di macOS.
- Sudah mengaktifkan versi PHP yang ingin digunakan di ServBay (misal PHP 8.3).
- Sudah mengaktifkan paket database dan cache yang akan dipakai di ServBay (misal MySQL, PostgreSQL, Redis, Memcached).
Membuat Proyek CodeIgniter
ServBay menyarankan untuk menyimpan semua proyek website Anda di direktori /Applications/ServBay/www
untuk memudahkan manajemen situs lokal oleh ServBay.
Instalasi Composer
ServBay sudah menyediakan Composer secara bawaan ketika diinstal, biasanya Anda tidak perlu menginstal ulang secara manual. Anda dapat langsung memakai perintah
composer
di terminal.Masuk ke Direktori Root Website
Buka Terminal, lalu masuk ke direktori root website yang direkomendasikan ServBay:
bashcd /Applications/ServBay/www
1Buat Proyek CodeIgniter
Gunakan Composer untuk membuat proyek CodeIgniter 4 baru. Misalnya beri nama direktori proyek
servbay-codeigniter-app
:bashcomposer create-project codeigniter4/appstarter servbay-codeigniter-app
1Composer akan mengunduh skeleton aplikasi CodeIgniter dan dependensi ke direktori
servbay-codeigniter-app
.Masuk ke Direktori Proyek
Masuk ke direktori proyek CodeIgniter yang baru dibuat:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1
Konfigurasi Awal
Konfigurasi Koneksi Database
Pengaturan koneksi database CodeIgniter terdapat di file app/Config/Database.php
. Sebelum menggunakan database, Anda perlu melakukan konfigurasi pada file ini.
Pertama, jika Anda berencana memakai database, pastikan sudah membuat database bernama servbay_codeigniter_app
melalui alat manajemen database ServBay (seperti Adminer atau phpMyAdmin, yang bisa diakses dari antarmuka ServBay).
Selanjutnya, edit file app/Config/Database.php
, cari array $default
, lalu isi detail koneksi sesuai jenis database yang digunakan di ServBay (misal MySQL atau PostgreSQL). Secara default, username dan password ServBay biasanya adalah root
dan password
.
Contoh konfigurasi MySQL:
php
public $default = [
'DSN' => '',
'hostname' => '127.0.0.1', // Database ServBay biasanya listen 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', // Tentukan 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
Untuk PostgreSQL, set DBDriver
ke 'Postgre'
, port umumnya 5432
, dan pengaturan charset mungkin perlu penyesuaian.
Konfigurasi Koneksi Cache (Memcached/Redis)
Jika ingin menggunakan Memcached atau Redis sebagai cache, konfigurasi dilakukan di file app/Config/Cache.php
.
Edit file app/Config/Cache.php
, lalu temukan bagian konfigurasi yang sesuai. Port default Memcached di ServBay adalah 11211
, Redis 6379
, dan biasanya tanpa password.
Contoh konfigurasi Memcached:
php
public $memcached = [
'host' => '127.0.0.1', // Memcached ServBay biasanya listen 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'; // Atur handler cache default ke redis
public $default = [ // Pengaturan Redis umumnya ada di array default
'host' => '127.0.0.1', // Redis ServBay biasanya listen di 127.0.0.1
'password' => null, // Redis ServBay default 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 isi konfigurasi sesuai dengan paket cache yang diaktifkan di ServBay.
Konfigurasi Web Server (Pengaturan Website ServBay)
Gunakan fitur Website ServBay untuk mengatur web server dan mengarahkannya ke proyek CodeIgniter Anda.
- Buka antarmuka aplikasi ServBay.
- Buka tab Websites.
- Klik tombol
+
di kiri bawah untuk menambah website baru. - Isi informasi website:
- Name (Nama): Masukkan nama yang mudah dikenali, misal
My First CodeIgniter Dev Site
. - Domain: Masukkan domain lokal yang akan diakses, misal
servbay-codeigniter-test.local
. ServBay secara otomatis memetakan domain.local
ke localhost. - Site Type (Tipe Website): Pilih
PHP
. - PHP Version (Versi PHP): Pilih versi PHP yang ingin digunakan, misal
8.3
. - Document Root (Root Dokumen): Ini langkah penting. File entry point CodeIgniter (
index.php
) ada di folderpublic
dalam direktori proyek. Jadi, Root direktori website harus diarahkan ke folderpublic
dalam proyek:/Applications/ServBay/www/servbay-codeigniter-app/public
.
- Name (Nama): Masukkan nama yang mudah dikenali, misal
- Klik Add untuk menyimpan pengaturan.
- ServBay mungkin meminta konfirmasi untuk menerapkan perubahan, klik OK/konfirmasi.
Langkah lebih detail lihat di Menambahkan Website Pertama.
Menambahkan Kode Contoh
Untuk memverifikasi bahwa proyek berjalan serta menguji koneksi database dan cache, kita akan memodifikasi controller default Home
di CodeIgniter dengan menambahkan beberapa method contoh.
Edit file app/Controllers/Home.php
dan ganti seluruh 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
{
/**
* Method default untuk homepage
*/
public function index(): string
{
// Tampilkan pesan sambutan sederhana
return '<h1>Hello ServBay and CodeIgniter!</h1><p>Your CodeIgniter project is running on ServBay.</p>';
}
/**
* Contoh method Memcached
*/
public function memcached(): string
{
try {
$cache = \Config\Services::cache();
// Coba simpan data 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.';
}
// Coba ambil data 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 lain-lain exception
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Contoh method Redis
*/
public function redis(): string
{
try {
$cache = \Config\Services::cache();
// Coba simpan data 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.';
}
// Coba ambil data 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 lain-lain exception
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Menulis data user ke database (MySQL/PostgreSQL)
*/
public function addUser(): string
{
try {
$db = \Config\Database::connect();
// Cek apakah tabel 'users' sudah ada (langkah pencegahan)
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// Insert data user
$data = [
'name' => 'ServBay Demo User',
'email' => 'user_' . time() . '@servbay.demo', // Buat email unik dengan time()
];
$db->table('users')->insert($data);
// Cek apakah insert berhasil (opsional, insert() biasanya return true)
// if ($db->affectedRows() > 0) {
return 'User added successfully: ' . $data['email'];
// } else {
// return 'Error: Failed to add user.';
// }
} catch (DatabaseException $e) {
// Tangkap exception terkait database
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Tangkap lain-lain exception
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' sudah ada
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// Query semua data user
$users = $db->table('users')->get()->getResult();
if (empty($users)) {
return 'No users found in the database.';
}
// Return user list dalam format JSON
return json_encode($users);
} catch (DatabaseException $e) {
// Tangkap exception terkait database
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Tangkap lain-lain exception
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 diperbarui ini memberikan output yang lebih jelas dan penanganan error dasar untuk membantu ketika terjadi error integrasi.
Konfigurasi Routing
Agar Anda dapat mengakses method contoh yang ditambahkan di controller Home
lewat URL, perlu menambahkan aturan routing pada file routing CodeIgniter.
Edit file app/Config/Routes.php
. Temukan bagian definisi $routes
, lalu tambahkan aturan routing berikut:
php
// ... aturan routing lainnya ...
// 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 lainnya ...
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 aturan routing ini ditambahkan ke definisi $routes
yang sudah ada tanpa menimpa isi lama.
Mengakses Website
Sekarang, proyek CodeIgniter Anda sudah terkonfigurasi dan berjalan di ServBay. Buka browser web dan akses domain yang sudah Anda atur sebelumnya:
Akses halaman utama:
https://servbay-codeigniter-test.local
Anda seharusnya melihat tampilan bertuliskanHello ServBay and CodeIgniter!
sebagai tanda website sudah berjalan di ServBay.Akses contoh Memcached:
https://servbay-codeigniter-test.local/memcached
Jika layanan Memcached dan konfigurasinya benar, Anda akan melihat output sepertiMemcached Test Success: Hello Memcached from CodeIgniter!
.Akses contoh Redis:
https://servbay-codeigniter-test.local/redis
Jika layanan Redis dan konfigurasinya benar, Anda akan melihat output sepertiRedis Test Success: Hello Redis from CodeIgniter!
.
Contoh Operasi Database (MySQL/PostgreSQL)
Sebelum menggunakan contoh database, jalankan perintah migration di CodeIgniter untuk membuat tabel users
.
Membuat Struktur Database (Menjalankan Migration)
Buka Terminal dan masuk ke direktori proyek CodeIgniter:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Buat File Migration: Gunakan CLI CodeIgniter untuk membuat file migration yang mendefinisikan struktur tabel
users
:bashphp spark make:migration create_users_table
1Ini akan membuat file PHP baru di folder
app/Database/Migrations
.Edit File Migration: Buka file migration yang baru dibuat (namanya seperti
YYYY-MM-DD-HHMMSS_CreateUsersTable.php
), lalu edit methodup()
untuk mendefinisikan kolom & index tabelusers
. Perhatikan, pada MySQL dan PostgreSQL sintaks default value untuk timestamp sedikit berbeda (CURRENT_TIMESTAMP
vsNOW()
), CodeIgniter menyediakanRawSql
untuk membantu. Berikut contoh pengisiannya:php<?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; use CodeIgniter\Database\RawSql; // Pastikan import 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 unik ], 'created_at' => [ 'type' => 'TIMESTAMP', // Pilih ekspresi default value sesuai jenis database // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP' : 'NOW()'), // Pilih otomatis ], '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()'), // Pilih otomatis ], ]); $this->forge->addKey('id', true); // id sebagai primary key $this->forge->createTable('users'); // buat tabel users } public function down() { // Untuk rollback migration, 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: Contoh di atas menggunakan logika sederhana untuk memilih sintaks default value timestamp secara otomatis sesuai platform database. Pada proyek nyata, Anda mungkin perlu strategi migration lebih mantap atau memisahkan migration untuk tiap database.
Jalankan Migration: Di terminal, jalankan migration untuk membuat tabel
users
:bashphp spark migrate
1Setelah sukses, di terminal akan muncul pesan migration berhasil. Anda juga dapat memeriksa lewat alat database ServBay (mis. Adminer) apakah tabel sudah terbentuk di database
servbay_codeigniter_app
.
Mengakses Contoh Database
Pastikan Anda sudah mengatur koneksi database dengan benar di app/Config/Database.php
dan sudah menjalankan migration untuk membuat tabel users
.
Tambah User ke Database: Akses
https://servbay-codeigniter-test.local/add-user
Setiap akses ke URL ini akan memasukkan satu user baru ke tabelusers
. Akan tampil pesan sepertiUser added successfully: [email protected]
.Daftar User dari Database: Akses
https://servbay-codeigniter-test.local/list-users
URL ini akan mengambil semua data di tabelusers
dan menampilkan dalam format JSON.
Kesimpulan
Dengan mengikuti langkah-langkah di atas, Anda telah berhasil membuat, mengkonfigurasi, dan menjalankan proyek CodeIgniter di lingkungan ServBay pada macOS. Anda telah belajar membuat proyek dengan Composer, mengatur Website ServBay ke direktori yang benar, melakukan koneksi database dan cache pada CodeIgniter, sampai menguji integrasi melalui kode contoh sederhana. ServBay mempermudah pembuatan dan manajemen lingkungan lokal, sehingga Anda dapat lebih fokus mengembangkan aplikasi CodeIgniter Anda.