Create and Run a CodeIgniter Project
What is CodeIgniter?
CodeIgniter is a lightweight, high-performance PHP web application development framework. It follows the Model-View-Controller (MVC) design pattern and is designed to help developers rapidly build feature-rich web applications. Thanks to its clean structure, great performance, and easy learning curve, CodeIgniter has become a favorite framework for many PHP developers.
Key Features and Advantages of CodeIgniter
- Lightweight Core: CodeIgniter's core system is extremely streamlined and only includes the essential components needed to run, ensuring extremely fast loading speed.
- Outstanding Performance: The framework is designed with efficiency in mind, capable of handling high-concurrency requests and delivering superior application performance.
- Easy to Learn: Clear documentation and an intuitive API lower the learning curve, making it easy for developers to pick up and master.
- Highly Flexible: Developers can freely select and integrate third-party libraries based on project needs, facilitating extension and customization.
- Active Community Support: Backed by a large and active developer community, offering abundant resources and support.
CodeIgniter is suitable for a wide range of development needs, from small projects to large enterprise applications, helping developers 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. It comes with PHP, databases (MySQL, PostgreSQL, MongoDB), caching (Redis, Memcached), web servers (Caddy, Nginx, Apache), and more, all with a convenient management interface. With ServBay, you can easily set up and manage a development environment for CodeIgniter projects.
This guide will walk you through using ServBay's PHP environment and Websites feature to create, configure, and run a CodeIgniter project, as well as demonstrate integration with multiple databases and caching services.
Prerequisites
Before you begin, please ensure you have completed the following:
- ServBay has been successfully installed and is running on macOS.
- The desired PHP version (e.g., PHP 8.3) is enabled in ServBay.
- The required database and cache packages (e.g., MySQL, PostgreSQL, Redis, Memcached) are enabled in ServBay.
Creating a CodeIgniter Project
ServBay recommends storing your website projects in the /Applications/ServBay/www
directory. This helps ServBay better manage your local sites.
Install Composer
ServBay comes with Composer pre-installed, so no manual installation is usually necessary. You can use the
composer
command directly in the terminal.Navigate to the Website Root Directory
Open the terminal and change to ServBay's recommended web root:
bashcd /Applications/ServBay/www
1Create a CodeIgniter Project
Use Composer to create a new CodeIgniter 4 project. Let's name the project directory
servbay-codeigniter-app
:bashcomposer create-project codeigniter4/appstarter servbay-codeigniter-app
1Composer will download the skeleton application and dependencies for CodeIgniter into the
servbay-codeigniter-app
directory.Enter the Project Directory
Change into your newly created CodeIgniter project directory:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1
Initial Configuration
Configuring the Database Connection
CodeIgniter's database configuration is located in the app/Config/Database.php
file. Before using any database features, you need to set your connection details in this file.
First, if you plan to use a database, make sure to create a database named servbay_codeigniter_app
using ServBay's database management tools (such as Adminer or phpMyAdmin, accessible through the ServBay app interface).
Next, edit the app/Config/Database.php
file, locate the $default
array, and fill in your connection details based on the database type you enabled in ServBay (e.g., MySQL or PostgreSQL). The default ServBay database username and password are typically root
and password
.
Here's an example of a MySQL configuration:
public $default = [
'DSN' => '',
'hostname' => '127.0.0.1', // ServBay DB typically listens on 127.0.0.1
'username' => 'root', // ServBay default username
'password' => 'password', // ServBay default password
'database' => 'servbay_codeigniter_app', // Your database name
'DBDriver' => 'MySQLi', // Set by 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
];
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
If you are using PostgreSQL, set DBDriver
to 'Postgre'
, port typically to 5432
, and adjust character set settings as needed.
Configuring Cache Connections (Memcached/Redis)
If you plan to use Memcached or Redis for caching, you need to configure them in the app/Config/Cache.php
file.
Edit the app/Config/Cache.php
file and find the relevant configuration sections. ServBay's Memcached listens on port 11211
by default, and Redis on port 6379
, usually with no password required.
Here's a Memcached configuration example:
public $memcached = [
'host' => '127.0.0.1', // ServBay Memcached usually listens on 127.0.0.1
'port' => 11211, // Memcached default port
'weight' => 1,
];
2
3
4
5
Redis configuration example:
public string $handler = 'redis'; // Set default cache handler to redis
public $default = [ // Redis config is usually in the default array
'host' => '127.0.0.1', // ServBay Redis usually listens on 127.0.0.1
'password' => null, // ServBay Redis has no password by default
'port' => 6379, // Redis default port
'timeout' => 0,
'database' => 0,
];
2
3
4
5
6
7
8
9
Make sure to configure the relevant sections according to the cache packages you've enabled.
Configuring the Web Server (ServBay Website Settings)
Use ServBay’s Websites 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 in the lower left to add a new website. - Enter your site details:
- Name: Enter a recognizable name, such as
My First CodeIgniter Dev Site
. - Domain: Specify the domain you want to use in your local browser, e.g.,
servbay-codeigniter-test.local
. ServBay will automatically resolve.local
domains to localhost. - Site Type: Select
PHP
. - PHP Version: Choose your preferred PHP version, e.g.,
8.3
. - Document Root: This is crucial. The CodeIgniter entry file (
index.php
) is inside thepublic
folder in your project root. So, Document Root must be set to thepublic
folder within your project directory:/Applications/ServBay/www/servbay-codeigniter-app/public
.
- Name: Enter a recognizable name, such as
- Click Add to save your settings.
- ServBay may prompt you to apply changes. Click to confirm.
For detailed configuration steps, refer to Add Your First Website.
Adding Sample Code
To verify your project is running correctly and test database and cache connections, let's modify CodeIgniter's default Home
controller and add some sample methods.
Edit app/Controllers/Home.php
and replace its contents with the code below:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\Database\Exceptions\DatabaseException; // Import DatabaseException class
use CodeIgniter\Cache\Exceptions\CacheException; // Import CacheException class
class Home extends Controller
{
/**
* Default home page 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();
// Try to save to the 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.';
}
// Try to retrieve from the 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) {
// Handle cache-related exceptions
return 'Cache Error: ' . $e->getMessage() . '. Ensure Memcached service is running and configured correctly.';
} catch (\Exception $e) {
// Handle any unexpected exceptions
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Redis example method
*/
public function redis(): string
{
try {
$cache = \Config\Services::cache();
// Try to save to the 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.';
}
// Try to retrieve from the 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) {
// Handle cache-related exceptions
return 'Cache Error: ' . $e->getMessage() . '. Ensure Redis service is running and configured correctly.';
} catch (\Exception $e) {
// Handle any unexpected exceptions
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
/**
* Write user data to the 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);
// Optionally 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) {
// Handle database-related exceptions
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Handle any unexpected 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 users list as JSON
return json_encode($users);
} catch (DatabaseException $e) {
// Handle database-related exceptions
return 'Database Error: ' . $e->getMessage() . '. Check database connection and table structure.';
} catch (\Exception $e) {
// Handle any unexpected exceptions
return 'An unexpected error occurred: ' . $e->getMessage();
}
}
}
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 clearer output and basic error handling to help with troubleshooting.
Configuring Routes
To make the new sample methods in the Home
controller accessible via URL, you'll need to add corresponding routes in CodeIgniter's routing file.
Edit app/Config/Routes.php
. Locate the $routes
definitions and add the following route rules:
// ... Other routes ...
// Memcached sample route
$routes->get('/memcached', 'Home::memcached');
// Redis sample route
$routes->get('/redis', 'Home::redis');
// Database sample routes
$routes->get('/add-user', 'Home::addUser');
$routes->get('/list-users', 'Home::listUsers');
// ... Other routes ...
2
3
4
5
6
7
8
9
10
11
12
13
Be sure to include these new routes in the existing $routes
definitions, without overwriting existing routes.
Accessing Your Website
Now your CodeIgniter project is configured and running on ServBay. Open your web browser and visit the domain you set up earlier:
Access the home page:
https://servbay-codeigniter-test.local
You should seeHello ServBay and CodeIgniter!
on the page, indicating your project is running successfully via ServBay's web server.Access the Memcached example:
https://servbay-codeigniter-test.local/memcached
If Memcached is running and configured correctly, you should see output similar toMemcached Test Success: Hello Memcached from CodeIgniter!
.Access the Redis example:
https://servbay-codeigniter-test.local/redis
If Redis is running and configured correctly, you should see output likeRedis Test Success: Hello Redis from CodeIgniter!
.
Database Operation Example (MySQL/PostgreSQL)
Before using the database examples, you need to run CodeIgniter's migration command to create the users
table.
Creating the Database Structure (Run Migration)
Open the terminal and navigate to your CodeIgniter project directory:
bashcd /Applications/ServBay/www/servbay-codeigniter-app
1Create a migration file: Use CodeIgniter's CLI tool to generate a migration defining the
users
table:bashphp spark make:migration create_users_table
1This creates a new PHP file in the
app/Database/Migrations
directory.Edit the migration file: Open the new migration file (its name will be something like
YYYY-MM-DD-HHMMSS_CreateUsersTable.php
), and edit theup()
method to define the columns and indexes for theusers
table.
Note: MySQL and PostgreSQL differ slightly in their default value syntax for automatic timestamp fields (CURRENT_TIMESTAMP
vsNOW()
). CodeIgniter'sRawSql
class can help with this. Example:php<?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; use CodeIgniter\Database\RawSql; // Ensure RawSql class 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 as unique ], 'created_at' => [ 'type' => 'TIMESTAMP', // Choose syntax for default value based on database platform // MySQL: 'default' => new RawSql('CURRENT_TIMESTAMP'), // PostgreSQL: 'default' => new RawSql('NOW()'), 'default' => new RawSql($this->db->getPlatform() === 'MySQLi' ? 'CURRENT_TIMESTAMP' : 'NOW()'), // Dynamic selection ], '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 selection ], ]); $this->forge->addKey('id', true); // Set id as primary key $this->forge->createTable('users'); // Create users table } public function down() { // Used to rollback migrations, drops the 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 above example uses simple logic to dynamically choose the correct timestamp default expression based on the database platform. In actual projects, you may want more robust migration strategies or maintain different migration files per database.
Run the migration: In the terminal, execute the following command to run the migrations and create the
users
table:bashphp spark migrate
1If successful, you should see a migration successful message in your terminal. You can also verify that the
users
table was created in theservbay_codeigniter_app
database using ServBay's database tools (such as Adminer).
Accessing the Database Examples
Ensure you have correctly configured your database connection in app/Config/Database.php
and 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 adds a new user to theusers
table. You should see output likeUser added successfully: [email protected]
.List users in the database: Visit
https://servbay-codeigniter-test.local/list-users
This URL will query all records from theusers
table and output them in JSON format.
Summary
By following the above steps, you've successfully created, configured, and run a CodeIgniter project in the ServBay environment on macOS. You've learned how to create a project with Composer, configure ServBay's Website feature to point to the correct directory, set up CodeIgniter's database and cache connections, and verify your integration through simple sample code. ServBay simplifies the setup and management of your local environment, allowing you to focus on developing your CodeIgniter applications.