Creating and Running a CodeIgniter Project
What is CodeIgniter?
CodeIgniter is a lightweight, high-performance PHP web application framework. It follows the Model-View-Controller (MVC) design pattern and is designed to help developers quickly build feature-rich web applications. CodeIgniter is favored by many PHP developers for its clean structure, outstanding performance, and ease of learning.
Key Features and Advantages of CodeIgniter
- Lightweight Core: CodeIgniter’s core system is exceptionally streamlined, containing only essential components for operation, resulting in fast load times.
- Exceptional Performance: The framework is engineered for efficiency, capable of handling high-concurrency requests and delivering great application performance.
- Easy to Learn: It offers clear documentation and an intuitive API, lowering the learning curve so developers can get up to speed quickly.
- Highly Flexible: Developers can freely choose and integrate third-party libraries as needed, making it easy to extend and customize features.
- Active Community Support: A large and vibrant developer community provides a wealth of resources and assistance.
CodeIgniter is suitable for projects ranging from small sites to large-scale enterprise applications, empowering developers to efficiently build high-quality web solutions.
Setting Up a CodeIgniter Development Environment with ServBay
ServBay is a local web development environment tool designed for macOS and Windows. It comes bundled with PHP, databases (MySQL, PostgreSQL, MongoDB), caching services (Redis, Memcached), and web servers (Caddy, Nginx, Apache), offering a convenient management interface. With ServBay, you can easily set up and manage everything you need for CodeIgniter development.
This guide will walk you through using ServBay’s PHP environment and Website feature to create, configure, and run a CodeIgniter project, as well as demonstrate how to integrate multiple databases and caching services.
Prerequisites
Before getting started, make sure that you have:
- Successfully installed and launched ServBay on macOS or Windows.
- Enabled the desired PHP version in ServBay (e.g., PHP 8.3).
- Enabled the database and caching packages you plan to use in ServBay (e.g., MySQL, PostgreSQL, Redis, Memcached).
Creating a CodeIgniter Project
ServBay recommends storing your site projects in the following directories for better management of local sites:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
Install Composer
ServBay includes Composer by default, so you typically don’t need to install it manually. The
composer
command is available directly in your terminal.Navigate to the Site Root Directory
Open your terminal and go to ServBay’s recommended root directory:
macOS:
bashcd /Applications/ServBay/www
1Windows:
cmdcd C:\ServBay\www
1Create a CodeIgniter Project
Use Composer to create a new CodeIgniter 4 project. We'll name the project directory
servbay-codeigniter-app
:bashcomposer create-project codeigniter4/appstarter servbay-codeigniter-app
1Composer will download the CodeIgniter skeleton app and its dependencies into the
servbay-codeigniter-app
directory.Enter the Project Directory
Move into the newly created project folder:
macOS:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Windows:
cmdcd C:\ServBay\www\servbay-codeigniter-app
1
Initial Configuration
Configuring the Database Connection
CodeIgniter’s database settings are found in app/Config/Database.php
. You’ll need to configure your connection details in this file before using the database.
First, make sure you’ve created a database named servbay_codeigniter_app
through ServBay’s database management tools (such as Adminer or phpMyAdmin, available via ServBay’s interface).
Next, edit the app/Config/Database.php
file. Locate the $default
array and fill out the connection details based on the database type you’ve enabled in ServBay (e.g., MySQL or PostgreSQL). ServBay’s default database username and password are typically root
and password
.
Here’s a sample configuration for MySQL:
php
public $default = [
'DSN' => '',
'hostname' => '127.0.0.1', // ServBay database usually listens on 127.0.0.1
'username' => 'root', // ServBay default username
'password' => 'password', // ServBay default password
'database' => 'servbay_codeigniter_app', // The database you created
'DBDriver' => 'MySQLi', // Set according to the database type; MySQL uses MySQLi or Pdo
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306, // MySQL default port
];
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
For PostgreSQL, DBDriver
should be set to 'Postgre'
, the port is usually 5432
, and you may need to adjust character set settings.
Configuring Cache Connections (Memcached/Redis)
If you plan to use Memcached or Redis for caching, configure them in app/Config/Cache.php
.
Open app/Config/Cache.php
and locate the relevant section. ServBay’s Memcached listens on port 11211
, Redis on 6379
, and typically neither requires a password.
Sample Memcached configuration:
php
public $memcached = [
'host' => '127.0.0.1', // ServBay Memcached usually listens on 127.0.0.1
'port' => 11211, // Memcached default port
'weight' => 1,
];
1
2
3
4
5
2
3
4
5
Sample Redis configuration:
php
public string $handler = 'redis'; // Set the default cache handler to redis
public $default = [ // Redis config usually under the default array
'host' => '127.0.0.1', // ServBay Redis usually listens on 127.0.0.1
'password' => null, // ServBay Redis default is no password
'port' => 6379, // Redis default port
'timeout' => 0,
'database' => 0,
];
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Be sure to configure the appropriate section depending on which cache package you’ve enabled.
Configuring the Web Server (ServBay Website Settings)
Use ServBay’s Website feature to configure the web server and point it to your CodeIgniter project.
- Open the ServBay application interface.
- Navigate to the Websites tab.
- Click the
+
button at the bottom left to add a new site. - Enter the following site details:
- Name: Choose a recognizable name, e.g.,
My First CodeIgniter Dev Site
. - Domain: Enter the local domain you want to use in your browser, e.g.,
servbay-codeigniter-test.local
. ServBay will automatically resolve.local
domains to your machine. - Site Type: Select
PHP
. - PHP Version: Select your preferred PHP version, e.g.,
8.3
. - Document Root: This is crucial. CodeIgniter’s entry file (
index.php
) is located in thepublic
folder under your project root. Therefore, set the Document Root to thepublic
folder inside your project directory:/Applications/ServBay/www/servbay-codeigniter-app/public
.
- Name: Choose a recognizable name, e.g.,
- Click the Add button to save your settings.
- ServBay may ask you to apply changes; click to confirm.
For detailed steps, see Adding Your First Website.
Adding Example Code
To verify that the project is running and test database and cache integration, let's modify CodeIgniter’s default Home
controller and add some sample methods.
Edit app/Controllers/Home.php
, replacing its contents with:
php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\Database\Exceptions\DatabaseException; // Import database exception class
use CodeIgniter\Cache\Exceptions\CacheException; // Import cache exception class
class Home extends Controller
{
/**
* Default homepage method
*/
public function index(): string
{
// Return a simple welcome message
return '<h1>Hello ServBay and CodeIgniter!</h1><p>Your CodeIgniter project is running on ServBay.</p>';
}
/**
* Memcached example method
*/
public function memcached(): string
{
try {
$cache = \Config\Services::cache();
// Attempt to save to cache
$success = $cache->save('servbay_memcached_key', 'Hello Memcached from CodeIgniter!', 60); // Cache for 60 seconds
if (!$success) {
return 'Error: Failed to save data to Memcached. Check Memcached service and configuration.';
}
// Attempt to retrieve from 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) {
// Catch cache-related exceptions
return 'Cache Error: ' . $e->getMessage() . '. Ensure Memcached service is running and configured correctly.';
} catch (\Exception $e) {
// Catch other potential exceptions
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Redis example method
*/
public function redis(): string
{
try {
$cache = \Config\Services::cache();
// Attempt to save to cache
$success = $cache->save('servbay_redis_key', 'Hello Redis from CodeIgniter!', 60); // Cache for 60 seconds
if (!$success) {
return 'Error: Failed to save data to Redis. Check Redis service and configuration.';
}
// Attempt to retrieve from 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) {
// Catch cache-related exceptions
return 'Cache Error: ' . $e->getMessage() . '. Ensure Redis service is running and configured correctly.';
} catch (\Exception $e) {
// Catch other potential exceptions
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Insert user data into database (MySQL/PostgreSQL)
*/
public function addUser(): string
{
try {
$db = \Config\Database::connect();
// Check if the 'users' table exists (basic safeguard)
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', // Use time() to create a unique email
];
$db->table('users')->insert($data);
// Optional: check if insert was successful (insert() usually returns true)
// if ($db->affectedRows() > 0) {
return 'User added successfully: ' . $data['email'];
// } else {
// return 'Error: Failed to add user.';
// }
} catch (DatabaseException $e) {
// Catch database-related exceptions
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Catch other potential exceptions
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Read user data from the database (MySQL/PostgreSQL)
*/
public function listUsers(): string
{
try {
$db = \Config\Database::connect();
// Check if the 'users' table exists
if (!$db->tableExists('users')) {
return 'Error: "users" table does not exist. Please run database migrations first.';
}
// Query all users
$users = $db->table('users')->get()->getResult();
if (empty($users)) {
return 'No users found in the database.';
}
// Return user list in JSON format
return json_encode($users);
} catch (DatabaseException $e) {
// Catch database-related exceptions
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Catch other potential exceptions
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
This updated controller provides clear output and basic error handling to help troubleshoot issues.
Setting Up Routes
To access the sample methods added to the Home
controller via URLs, you’ll need to add corresponding route rules in CodeIgniter’s routing file.
Edit app/Config/Routes.php
. Find the $routes
definition section and add the following route rules:
php
// ... other route rules ...
// Memcached example route
$routes->get('/memcached', 'Home::memcached');
// Redis example route
$routes->get('/redis', 'Home::redis');
// Database example routes
$routes->get('/add-user', 'Home::addUser');
$routes->get('/list-users', 'Home::listUsers');
// ... other route rules ...
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
Make sure these new routes are added to the existing $routes
definition without overwriting any original content.
Accessing Your Site
Your CodeIgniter project is now configured and running on ServBay. Open your web browser and access your site using the domain name you set up:
Homepage:
https://servbay-codeigniter-test.local
You should see a page displayingHello ServBay and CodeIgniter!
, confirming your project is running correctly via ServBay’s web server.Memcached Example:
https://servbay-codeigniter-test.local/memcached
If Memcached is running and configured, you’ll see output likeMemcached Test Success: Hello Memcached from CodeIgniter!
.Redis Example:
https://servbay-codeigniter-test.local/redis
If Redis is running and configured, you’ll see output likeRedis Test Success: Hello Redis from CodeIgniter!
.
Database Operation Example (MySQL/PostgreSQL)
Before using the database example, you’ll need to run CodeIgniter’s migration command to create the users
table.
Creating the Database Structure (Running Migrations)
Open a terminal and navigate to your CodeIgniter project directory:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Create a Migration File: Use CodeIgniter’s CLI to generate a migration file that defines the structure for the
users
table:bashphp spark make:migration create_users_table
1This creates a new PHP file under
app/Database/Migrations
.Edit the Migration File: Open the newly created migration file (filename like
YYYY-MM-DD-HHMMSS_CreateUsersTable.php
) and edit theup()
method to define the columns and indices for theusers
table. Note that MySQL and PostgreSQL use different syntax for default timestamp fields (CURRENT_TIMESTAMP
vsNOW()
), and CodeIgniter’sRawSql
helps address this. Here is a sample:php<?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; use CodeIgniter\Database\RawSql; // Ensure RawSql is imported 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, // Set email field as unique ], 'created_at' => [ 'type' => 'TIMESTAMP', // Choose the appropriate default expression by database type // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP' : 'NOW()'), // Dynamic choice ], '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()'), // Dynamic choice ], ]); $this->forge->addKey('id', true); // Set id as primary key $this->forge->createTable('users'); // Create users table } public function down() { // Rollback migration; drop users table $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
51Note: The sample above uses a simple logic to dynamically select timestamp default value syntax based on the database platform. In real projects, you may want a more robust migration strategy or maintain different migration files for different databases.
Run Migrations: Execute the following command in the terminal to create the
users
table:bashphp spark migrate
1On success, you should see output indicating migration ran successfully. You can also check the
servbay_codeigniter_app
database via ServBay's management tools (such as Adminer) to confirm theusers
table exists.
Using the Database Example
Make sure your database connection info in app/Config/Database.php
is correct, and you have run the migration to create the users
table.
Add a User to the Database: Visit
https://servbay-codeigniter-test.local/add-user
Each visit inserts a new user record into theusers
table. You’ll see output likeUser added successfully: user_XXXXXXXXXX@servbay.demo
.List Users in the Database: Visit
https://servbay-codeigniter-test.local/list-users
This URL queries all records from theusers
table and outputs a JSON array with user data.
Summary
By following these steps, you’ve successfully created, configured, and run a CodeIgniter project in ServBay on macOS (or Windows). You learned how to use Composer to create a project, configure ServBay Websites to point to the correct project directory, set up CodeIgniter’s database and cache connections, and validate database and cache integration using straightforward sample code. ServBay streamlines the process of setting up and managing local environments, letting you focus on developing your CodeIgniter application.