codeigniter/framework
CodeIgniter is a lightweight PHP web framework focused on speed, simplicity, and small footprint. It offers MVC structure, clean routing, security features, database tools, and helpers—ideal for building fast, maintainable apps without heavy dependencies.
Installation
composer create-project codeigniter4/appstarter my-project
composer require codeigniter4/framework
Project Structure
app/ – Core application logic (Models, Controllers, Views, Libraries).public/ – Web root (entry point: index.php).writable/ – Configs, caches, logs (ensure permissions: chmod -R 775 writable).First Use Case: Hello World
// app/Controllers/Home.php
namespace App\Controllers;
class Home extends BaseController {
public function index() {
return view('welcome_message');
}
}
// app/Views/welcome_message.php
<h1>Hello, CodeIgniter!</h1>
php spark serve
http://localhost:8080.Configuration
app/Config/ files (e.g., App.php, Database.php)..env (copy .env.example first).Routing
app/Config/Routes.php:
$routes->get('/', 'Home::index');
BaseController; use dependency injection (DI) for services.
class UserController extends BaseController {
public function __construct(private UserModel $userModel) {}
}
BaseModel for database interactions.
class UserModel extends BaseModel {
protected $table = 'users';
protected $allowedFields = ['name', 'email'];
}
view() helper or BaseController's render() method.
return view('user/profile', ['user' => $user]);
app/Config/Services.php:
services => [
'auth' => \App\Services\AuthService::class,
],
public function __construct(private AuthService $auth) {}
$users = $db->table('users')->where('active', 1)->get();
php spark migrate
Define migrations in app/Database/Migrations/.Validation library:
$rules = [
'email' => 'required|valid_email',
'password' => 'required|min_length[8]',
];
$validation = \Config\Services::validation();
if (!$validation->run($rules, $data)) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
JSONResponse for APIs:
return $this->response->setJSON([
'status' => 'success',
'data' => $users,
]);
Filter for API input sanitization.app/Config/Cache.php.Cache service:
$cache = \Config\Services::cache();
$data = $cache->get('key');
$cache->save('key', $data, 60);
app/Config/Events.php.
Events::on('preSystemShutdown', function () {
log_message('info', 'System shutting down...');
});
before/after hooks in controllers or globally in app/Config/Filters.php.app/Config/Services.php:
'library' => [
'parser' => \CodeIgniter\Parser\Parser::class,
'session' => \CodeIgniter\Session\Session::class,
],
Services facade:
$session = service('session');
BaseCommand:
// app/Commands/Example.php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
class Example extends BaseCommand {
public $group = 'custom';
public $name = 'example';
protected $description = 'Example command';
public function run() {
$this->output->writeln('Hello from CLI!');
}
}
app/Config/Commands.php and run:
php spark example
phpunit (included):
composer test
tests/ directory:
// tests/Unit/HomeTest.php
public function testIndex() {
$response = $this->get('/');
$response->assertOK();
}
Security helper for XSS/CSRF protection:
echo esc($userInput); // Escape output
csrf_token(); // In forms
app/Config/Security.php.Case Sensitivity
Autoloading Issues
composer dump-autoload runs after adding new classes.autoload.psr-4 in composer.json includes app/.Database Transactions
db->transStart()/transComplete() for multi-query transactions:
$db->transStart();
try {
$db->table('users')->insert($data);
$db->table('logs')->insert(['user_id' => $userId]);
$db->transComplete();
} catch (\Exception $e) {
$db->transRollback();
}
Session Handling
session driver in app/Config/Sessions.php.writable/sessions is writable (chmod 775).Route Caching
php spark route:clear
Model Relationships
hasMany, belongsTo, etc., but ensure foreign keys match:
protected $hasMany = ['posts' => PostModel::class];
File Uploads
app/Config/Validation.php:
'upload' => 'uploaded[file]|max_size[file,1024]|mime_in[file,image/jpg,image/png]',
Environment Switching
.env for environment-specific configs (e.g., APP_ENV=development).rootPath(), baseURL().Error Logging
writable/logs/ for errors.app/Config/App.php:
debugToolbar => env('CI_DEBUG_TOOLBAR', true),
Debug Toolbar
codeigniter4-debugbar for a PHP Debug Bar:
composer require --dev peridot-php/codeigniter4-debugbar
Var Dumping
var_dump() or dd() (from Debug helper):
dd($variable); // Dump and die
Query Logging
app/Config/Database.php:
'debug' => env('CI_DEBUG_DATABASE', true),
Route Debugging
php spark route:list
Custom Libraries
app/Libraries/ and autoload in composer.json:
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
Custom Helpers
app/Helpers/ and register in app/Config/Autoloader.php:
$psr4['App\\Helpers'] = APPPATH . 'Helpers';
Custom Commands
BaseCommand (see CLI Tasks above).Custom Filters
How can I help you explore Laravel packages today?