
Codeigniter
- 51 installs
- 3 repo stars
- Updated April 26, 2026
- yasserstudio/codeigniter-skills
Helps with ai & agent building tasks.
About
codeigniter is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- codeigniter
- AI & Agent Building
- AI-coding skill
Codeigniter by the numbers
- 51 all-time installs (skills.sh)
- +8 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #7,162 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/yasserstudio/codeigniter-skills --skill codeigniterAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 51 |
|---|---|
| repo stars | ★ 3 |
| Last updated | April 26, 2026 |
| Repository | yasserstudio/codeigniter-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
CodeIgniter Development
You are a CodeIgniter expert. You work with both CI3 (3.1.x) and CI4 (4.x, latest stable 4.7.x) and understand their fundamental architectural differences. Always identify which version the project uses before writing any code.
For deep dives on version-specific features, see:
- CI3 deep dive — file uploads, email, caching, pagination, libraries, HMVC, hooks, helpers, logging
- CI4 deep dive — REST controllers, entities, filters, migrations, seeders, uploads, email, caching, services, events, views, cells, Spark CLI, testing, Shield auth, content negotiation
- Deployment & migration — server config, production checklist, full CI3→CI4 migration table
Version Detection
| Signal | Version |
|---|---|
system/core/CodeIgniter.php exists | CI3 |
$this->load->model() / $this->load->view() | CI3 |
application/config/config.php | CI3 |
app/Config/App.php exists | CI4 |
namespace App\Controllers; in controllers | CI4 |
spark CLI at project root | CI4 |
composer.json requires codeigniter4/framework | CI4 |
---
CI3 — Core Patterns
Project Structure
project/
├── application/
│ ├── config/ # autoload.php, config.php, database.php, routes.php, hooks.php
│ ├── controllers/
│ ├── models/
│ ├── views/
│ ├── libraries/
│ ├── helpers/
│ ├── hooks/
│ ├── core/ # MY_Controller, MY_Model overrides
│ └── third_party/
├── system/ # framework core — never edit
└── index.php # front controllerControllers
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Products extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('product_model');
$this->load->helper('url');
}
public function index()
{
$data['products'] = $this->product_model->get_all();
$this->load->view('products/index', $data);
}
public function view($id)
{
$data['product'] = $this->product_model->get($id);
if (empty($data['product'])) {
show_404();
}
$this->load->view('products/view', $data);
}
}Rules: Class name MUST match filename (first letter uppercase). Always call parent::__construct(). On Linux, filenames are case-sensitive.
Models
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Product_model extends CI_Model
{
protected $table = 'products';
public function get_all()
{
return $this->db->get($this->table)->result();
}
public function get($id)
{
return $this->db->get_where($this->table, ['id' => $id])->row();
}
public function insert($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($id, $data)
{
$this->db->where('id', $id);
return $this->db->update($this->table, $data);
}
public function delete($id)
{
return $this->db->delete($this->table, ['id' => $id]);
}
}Query Builder
// SELECT with chaining
$results = $this->db
->select('p.*, c.name as category_name')
->from('products p')
->join('categories c', 'c.id = p.category_id', 'left')
->where('p.active', 1)
->where('p.price >', 10)
->order_by('p.name', 'ASC')
->limit(20, $offset)
->get()
->result();
// INSERT / UPDATE / DELETE
$this->db->insert('products', ['name' => $name, 'price' => $price]);
$this->db->where('id', $id)->update('products', ['price' => $new_price]);
$this->db->where('id', $id)->delete('products');
// Transactions
$this->db->trans_start();
$this->db->insert('orders', $order_data);
$this->db->insert('order_items', $item_data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) { /* failed */ }
// Raw query (always bind params)
$this->db->query('SELECT * FROM products WHERE slug = ?', [$slug]);Routing
$route['default_controller'] = 'home';
$route['404_override'] = 'errors/page_missing';
$route['products'] = 'catalog/index';
$route['products/(:num)'] = 'catalog/view/$1';
$route['api/products/(:any)'] = 'api/products/$1';Input & Security
// ALWAYS use $this->input — never raw $_POST/$_GET
$name = $this->input->post('name', TRUE); // TRUE = XSS filter
$id = $this->input->get('id');
// CSRF — enable in config.php
$config['csrf_protection'] = TRUE;
// Output escaping in views
<?php echo html_escape($user_input); ?>Form Validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|min_length[3]|max_length[255]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
if ($this->form_validation->run() === FALSE) {
$this->load->view('form', $data);
} else {
$this->product_model->insert($this->input->post());
redirect('products');
}Sessions
$this->session->set_userdata('user_id', $id);
$user_id = $this->session->userdata('user_id');
$this->session->set_flashdata('success', 'Product created.');---
CI4 — Core Patterns
Project Structure
project/
├── app/
│ ├── Config/ # App.php, Database.php, Routes.php, Filters.php, Services.php, Events.php
│ ├── Controllers/ # BaseController.php
│ ├── Models/
│ ├── Views/
│ ├── Filters/
│ ├── Entities/
│ ├── Cells/
│ ├── Commands/
│ ├── Database/ # Migrations/, Seeds/
│ └── Language/
├── public/ # web root — point server here
│ └── index.php
├── writable/ # cache, logs, session — must be writable by web server
├── tests/
├── .env
├── spark # CLI tool
└── composer.jsonControllers
<?php
namespace App\Controllers;
class Products extends BaseController
{
public function index()
{
$model = model('ProductModel');
return view('products/index', ['products' => $model->findAll()]);
}
public function show($id = null)
{
$product = model('ProductModel')->find($id);
if ($product === null) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
return view('products/show', ['product' => $product]);
}
public function create()
{
if (! $this->validate([
'name' => 'required|min_length[3]|max_length[255]',
'price' => 'required|numeric|greater_than[0]',
])) {
return view('products/create', ['validation' => $this->validator]);
}
model('ProductModel')->insert($this->request->getPost());
return redirect()->to('/products')->with('success', 'Product created.');
}
}Models
<?php
namespace App\Models;
use CodeIgniter\Model;
class ProductModel extends Model
{
protected $table = 'products';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $allowedFields = ['name', 'price', 'category_id', 'active'];
protected $validationRules = [
'name' => 'required|min_length[3]|max_length[255]',
'price' => 'required|numeric|greater_than[0]',
];
}Critical: $allowedFields is mandatory — fields not listed are silently dropped on insert/update. This prevents mass assignment.
Query Builder
$db = db_connect();
// SELECT with joins + pagination
$model = model('ProductModel');
$data = [
'products' => $model->where('active', 1)->paginate(20),
'pager' => $model->pager,
];
// Raw builder
$results = $db->table('products')
->select('products.*, categories.name as category')
->join('categories', 'categories.id = products.category_id', 'left')
->where('products.active', 1)
->orderBy('products.name', 'ASC')
->get()
->getResultArray();
// Transactions
$db->transStart();
$db->table('orders')->insert($order_data);
$db->table('order_items')->insert($item_data);
$db->transComplete();
if (! $db->transStatus()) { /* failed */ }Routing
$routes->get('/', 'Home::index');
$routes->get('products', 'Products::index');
$routes->get('products/(:num)', 'Products::show/$1');
$routes->post('products', 'Products::create');
$routes->resource('products'); // generates all CRUD routes
$routes->group('api', ['namespace' => 'App\Controllers\Api', 'filter' => 'apiauth'], function ($routes) {
$routes->resource('products');
});
$routes->get('admin/(:any)', 'Admin::$1', ['filter' => 'auth']);Input & Security
// ALWAYS use $this->request — never raw $_POST/$_GET
$name = $this->request->getPost('name');
$id = $this->request->getGet('id');
$data = $this->request->getJSON(true); // JSON API bodies → array
// Output escaping in views — context-aware
<?= esc($user_input) ?>
<?= esc($value, 'attr') ?>
<?= esc($value, 'js') ?>Sessions
$session = session();
$session->set('user_id', $id);
$userId = $session->get('user_id');
$session->setFlashdata('success', 'Done.');
$session->setTempdata('otp', $code, 300); // auto-expires in 5 minutes---
Security Checklist (Both Versions)
- [ ] Never use raw
$_POST/$_GET— use input class (CI3) or$this->request(CI4) - [ ] Enable CSRF protection; exempt only stateless API endpoints
- [ ] Use query builder or bound parameters — never concatenate SQL
- [ ] Escape output:
html_escape()(CI3) oresc()(CI4) in views - [ ] Set
db_debug = FALSE(CI3) /CI_ENVIRONMENT = production(CI4) on prod - [ ] Keep
system/(CI3) or project root (CI4) outside web root - [ ] Use
$allowedFieldsin CI4 models to prevent mass assignment - [ ] Validate file uploads — check MIME type, not just extension
- [ ] Set secure session config:
databasedriver,httponly,secureflags - [ ] Use
esc($var, 'attr')for HTML attributes,esc($var, 'js')for JS contexts - [ ] Set
Content-Security-Policyheaders for production - [ ] Use HTTPS everywhere —
app.forceGlobalSecureRequests = truein CI4 - [ ] Never expose stack traces in production
---
CI3 → CI4 Quick Reference
| CI3 | CI4 |
|---|---|
$this->load->model('x') | model('XModel') or DI |
$this->load->view('x', $data) | return view('x', $data) |
$this->load->library('x') | service('x') or new X() |
$this->input->post('x') | $this->request->getPost('x') |
$this->db->get('table') | $db->table('table')->get() |
$query->result() / ->row() | $query->getResult() / ->getRow() |
$query->result_array() | $query->getResultArray() |
redirect('url') | return redirect()->to('url') |
show_404() | throw PageNotFoundException::forPageNotFound() |
$this->session->userdata('x') | session()->get('x') |
html_escape($x) | esc($x) |
$route['x'] = 'y' | $routes->get('x', 'Y::method') |
Hooks ($hook[]) | Filters (middleware) |
CI_Controller / CI_Model | BaseController / CodeIgniter\Model |
| No namespaces | PSR-4 namespaces |
| No CLI generator | php spark make:* |
See deployment.md for the full 30+ mapping migration table, server configuration, and production deployment checklist.
CodeIgniter 3 — Deep Dive
Extended CI3 patterns beyond the core SKILL.md. Load this reference when working on CI3-specific features like file uploads, email, caching, HMVC, or custom libraries.
File Uploads
public function upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png|pdf';
$config['max_size'] = 2048; // KB
$config['max_width'] = 1920;
$config['max_height'] = 1080;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (! $this->upload->do_upload('userfile')) {
$error = $this->upload->display_errors();
$this->load->view('upload_form', ['error' => $error]);
} else {
$data = $this->upload->data();
$this->load->view('upload_success', $data);
}
}Upload data keys: file_name, file_type, file_path, full_path, raw_name, orig_name, file_ext, file_size, is_image, image_width, image_height.
$this->load->library('email');
$this->email->from('you@example.com', 'Your Name');
$this->email->to('recipient@example.com');
$this->email->cc('cc@example.com');
$this->email->subject('Order Confirmation');
$this->email->message('<h1>Your Order</h1><p>Details here.</p>');
$this->email->set_mailtype('html');
$this->email->attach('/path/to/invoice.pdf');
if (! $this->email->send()) {
echo $this->email->print_debugger();
}SMTP config in application/config/email.php:
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.example.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'user@example.com';
$config['smtp_pass'] = 'password';
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';Caching
$this->load->driver('cache', ['adapter' => 'file', 'backup' => 'file']);
$data = $this->cache->get('products_list');
if ($data === FALSE) {
$data = $this->product_model->get_all();
$this->cache->save('products_list', $data, 3600);
}
$this->cache->delete('products_list');
// Page caching (output cache) — in controller method
$this->output->cache(60); // cache full page for 60 minutesAvailable drivers: apc, file, memcached, redis, dummy.
Pagination
$this->load->library('pagination');
$config['base_url'] = site_url('products/index');
$config['total_rows'] = $this->product_model->count_all();
$config['per_page'] = 20;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$offset = $this->uri->segment(3, 0);
$data['products'] = $this->product_model->get_page($config['per_page'], $offset);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('products/index', $data);Custom Libraries
// application/libraries/My_cart.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class My_cart
{
protected $CI;
public function __construct($params = [])
{
$this->CI =& get_instance();
}
public function get_total()
{
return $this->CI->db->select_sum('price')->get('cart_items')->row()->price;
}
}
// Usage
$this->load->library('my_cart');
$total = $this->my_cart->get_total();HMVC (Modular Extensions)
Many CI3 apps use wiredesignz/hmvc:
application/modules/
├── auth/
│ ├── controllers/Auth.php
│ ├── models/Auth_model.php
│ └── views/login.php
├── products/
│ ├── controllers/Products.php
│ ├── models/Product_model.php
│ └── views/index.phpCross-module calls: Modules::run('auth/check') or $this->load->module('auth').
Hooks
// config/hooks.php
$hook['post_controller_constructor'][] = [
'class' => 'Auth_hook',
'function' => 'check_login',
'filename' => 'Auth_hook.php',
'filepath' => 'hooks',
];Logging
// In config.php, set threshold (0 = off, 1 = errors, 2 = +debug, 3 = +info, 4 = all)
$config['log_threshold'] = 1;
log_message('error', 'Something broke: ' . $error_msg);
log_message('debug', 'Variable dump: ' . print_r($data, TRUE));
log_message('info', 'User ' . $user_id . ' logged in');Common Helpers
// URL
echo base_url('assets/css/style.css');
echo site_url('products/view/5');
redirect('products');
// String
$this->load->helper('string');
$random = random_string('alnum', 16);
// Array
$value = element('key', $array, 'default');
// Date
echo mdate('%Y-%m-%d %H:%i', now());
// Text
echo word_limiter($text, 25);
echo character_limiter($text, 100);Extended Query Builder
// INSERT BATCH
$this->db->insert_batch('products', [
['name' => 'A', 'price' => 10],
['name' => 'B', 'price' => 20],
]);
// WHERE IN / LIKE
$this->db->where_in('id', [1, 2, 3])->get('products')->result();
$this->db->like('name', $search)->get('products')->result();
// GROUP BY + HAVING
$this->db->select('category_id, COUNT(*) as total')
->group_by('category_id')
->having('total >', 5)
->get('products')
->result();
// COUNT
$count = $this->db->where('active', 1)->count_all_results('products');
// SUBQUERY (no native builder — use raw)
$this->db->where('category_id IN (SELECT id FROM categories WHERE active = 1)', NULL, FALSE);Common CI3 Pitfalls
1. Case sensitivity on Linux: product_model.php won't autoload if class is Product_model. Always match exactly. 2. `$this->load` before parent constructor: Call parent::__construct() first. 3. Raw `$_POST`/`$_GET`: Always use $this->input->post() — returns NULL on missing keys. 4. Forgetting CSRF in AJAX: Include csrf_token in AJAX requests or exempt specific URIs. 5. Database config in production: Set $db['default']['db_debug'] = FALSE. 6. `$autoload` bloat: Only autoload what every request needs. Load per-controller otherwise. 7. Overwriting `system/`: Never edit files in system/ — extend via application/core/MY_* classes.
CodeIgniter 4 — Deep Dive
Extended CI4 patterns beyond the core SKILL.md. Load this reference when working on CI4-specific features like REST controllers, migrations, testing, Shield auth, services, events, view layouts, or Spark CLI.
RESTful Resource Controllers
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class ProductsApi extends ResourceController
{
protected $modelName = 'App\Models\ProductModel';
protected $format = 'json';
public function index() { return $this->respond($this->model->findAll()); }
public function show($id = null) { return $this->respond($this->model->find($id)); }
public function create()
{
$data = $this->request->getJSON(true);
if (! $this->model->insert($data)) {
return $this->failValidationErrors($this->model->errors());
}
return $this->respondCreated(['id' => $this->model->getInsertID()]);
}
public function update($id = null)
{
$data = $this->request->getJSON(true);
if (! $this->model->update($id, $data)) {
return $this->failValidationErrors($this->model->errors());
}
return $this->respondUpdated(['id' => $id]);
}
public function delete($id = null)
{
$this->model->delete($id);
return $this->respondDeleted(['id' => $id]);
}
}Response helpers: respond($data, 200), respondCreated($data), respondUpdated($data), respondDeleted($data), respondNoContent(), fail($messages, 400), failNotFound(), failValidationErrors($errors), failForbidden(), failUnauthorized(), failServerError().
Entities
<?php
namespace App\Entities;
use CodeIgniter\Entity\Entity;
class Product extends Entity
{
protected $casts = [
'id' => 'integer',
'price' => 'float',
'active' => 'boolean',
];
public function setName(string $name): self
{
$this->attributes['name'] = trim($name);
$this->attributes['slug'] = url_title($name, '-', true);
return $this;
}
}Set protected $returnType = Product::class; in the model.
Model Callbacks
protected $beforeInsert = ['generateSlug'];
protected $beforeUpdate = ['generateSlug'];
protected function generateSlug(array $data): array
{
if (isset($data['data']['name'])) {
$data['data']['slug'] = url_title($data['data']['name'], '-', true);
}
return $data;
}Available: beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeFind, afterFind, beforeDelete, afterDelete, beforeInsertBatch, afterInsertBatch, beforeUpdateBatch, afterUpdateBatch.
Filters (Middleware)
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (! session()->get('logged_in')) {
return redirect()->to('/login');
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {}
}Register in app/Config/Filters.php:
public array $aliases = [
'auth' => \App\Filters\AuthFilter::class,
'csrf' => \CodeIgniter\Filters\CSRF::class,
];
public array $filters = [
'auth' => ['before' => ['admin/*', 'dashboard']],
'csrf' => ['before' => ['/*'], 'except' => ['api/*']],
];Migrations
php spark make:migration CreateProductsTable<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateProductsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
'name' => ['type' => 'VARCHAR', 'constraint' => 255],
'slug' => ['type' => 'VARCHAR', 'constraint' => 255],
'price' => ['type' => 'DECIMAL', 'constraint' => '10,2', 'default' => 0],
'category_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'active' => ['type' => 'TINYINT', 'constraint' => 1, 'default' => 1],
'created_at' => ['type' => 'DATETIME', 'null' => true],
'updated_at' => ['type' => 'DATETIME', 'null' => true],
'deleted_at' => ['type' => 'DATETIME', 'null' => true],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('slug');
$this->forge->addForeignKey('category_id', 'categories', 'id', 'SET NULL', 'CASCADE');
$this->forge->createTable('products');
}
public function down()
{
$this->forge->dropTable('products');
}
}Database Seeding
php spark make:seeder ProductSeeder<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class ProductSeeder extends Seeder
{
public function run()
{
$data = [
['name' => 'Widget A', 'price' => 9.99, 'active' => 1, 'created_at' => date('Y-m-d H:i:s')],
['name' => 'Widget B', 'price' => 19.99, 'active' => 1, 'created_at' => date('Y-m-d H:i:s')],
];
$this->db->table('products')->insertBatch($data);
$this->call('CategorySeeder');
}
}File Uploads
public function upload()
{
$file = $this->request->getFile('userfile');
if (! $file->isValid()) {
return redirect()->back()->with('error', $file->getErrorString());
}
if (! $this->validateData([], [
'userfile' => 'uploaded[userfile]|max_size[userfile,2048]|ext_in[userfile,jpg,jpeg,png,pdf]|mime_in[userfile,image/jpeg,image/png,application/pdf]',
])) {
return redirect()->back()->with('errors', $this->validator->getErrors());
}
$path = $file->store('uploads/'); // auto YYYYMMDD subdirs + random name
return redirect()->back()->with('success', 'File uploaded.');
}
// Multiple files
$files = $this->request->getFileMultiple('images');
foreach ($files as $file) {
if ($file->isValid() && ! $file->hasMoved()) {
$file->move(WRITEPATH . 'uploads');
}
}UploadedFile methods: isValid(), hasMoved(), getName(), getClientName(), getClientExtension(), guessExtension(), getMimeType(), getSize(), move($path, $name), store($folder), getRandomName().
$email = service('email');
$email->setFrom('you@example.com', 'Your Name');
$email->setTo('recipient@example.com');
$email->setSubject('Order Confirmation');
$email->setMessage('<h1>Your Order</h1><p>Details here.</p>');
$email->setAltMessage('Your Order - Details here.');
$email->attach('/path/to/invoice.pdf');
// Inline image (separate email — setMessage overwrites previous)
$email->clear();
$email->attach('/path/to/logo.png');
$cid = $email->setAttachmentCID('/path/to/logo.png');
$email->setMessage('<img src="cid:' . $cid . '"> <p>Content with inline image</p>');
if (! $email->send()) {
log_message('error', $email->printDebugger(['headers']));
}
$email->clear();Configure in .env:
email.protocol = smtp
email.SMTPHost = smtp.example.com
email.SMTPUser = user@example.com
email.SMTPPass = password
email.SMTPPort = 587
email.SMTPCrypto = tls
email.mailType = htmlCaching
$cache = service('cache');
// Remember pattern (get or compute + cache)
$products = $cache->remember('products_list', 3600, function () {
return model('ProductModel')->findAll();
});
$cache->delete('products_list');
$cache->deleteMatching('products_*'); // file, redis, predis only
$cache->increment('page_views', 1);
$cache->decrement('stock_count', 1);
$cache->clean(); // wipe allDrivers: file, redis, memcached, predis, wincache, dummy. Configure in app/Config/Cache.php.
Services (Dependency Injection)
// Shared instance (singleton)
$email = service('email');
// New instance
$email = single_service('email');
// Custom service — app/Config/Services.php
public static function paymentGateway(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('paymentGateway');
}
return new \App\Libraries\StripeGateway(config('Payment')->apiKey);
}
// Usage
$gateway = service('paymentGateway');Events
// app/Config/Events.php
use CodeIgniter\Events\Events;
Events::on('user_registered', function ($user) {
service('email')->setTo($user->email)->setSubject('Welcome!')->setMessage(view('emails/welcome', ['user' => $user]))->send();
});
Events::on('order_placed', 'App\Listeners\UpdateInventory::handle', 5); // priority
// Trigger
Events::trigger('user_registered', $user);
// Built-in: pre_system, post_controller_constructor, post_system, email, DBQuery, migrateView Layouts & Partials
Layout (app/Views/layouts/default.php):
<!doctype html>
<html>
<head><title><?= $this->renderSection('title') ?></title></head>
<body>
<?= $this->include('partials/header') ?>
<main><?= $this->renderSection('content') ?></main>
<?= $this->include('partials/footer') ?>
</body>
</html>Child view:
<?= $this->extend('layouts/default') ?>
<?= $this->section('title') ?>Products<?= $this->endSection() ?>
<?= $this->section('content') ?>
<h1>Products</h1>
<?php foreach ($products as $product): ?>
<div><?= esc($product['name']) ?></div>
<?php endforeach; ?>
<?= $this->endSection() ?>View Cells
php spark make:cell AlertMessageCell// app/Cells/AlertMessageCell.php
namespace App\Cells;
use CodeIgniter\View\Cells\Cell;
class AlertMessageCell extends Cell
{
public string $type = 'info';
public string $message = '';
}// app/Cells/alert_message_cell.php
<div class="alert alert-<?= esc($type) ?>"><?= esc($message) ?></div>// Usage
<?= view_cell('AlertMessageCell', ['type' => 'success', 'message' => 'Saved!']) ?>
<?= view_cell('AlertMessageCell', ['type' => 'info', 'message' => 'Hello'], 3600) ?> <!-- cached -->Custom Spark Commands
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
class AppInfo extends BaseCommand
{
protected $group = 'App';
protected $name = 'app:info';
protected $description = 'Displays application information';
protected $usage = 'app:info [--env]';
protected $options = ['--env' => 'Show environment details'];
public function run(array $params)
{
CLI::write('App: ' . config('App')->appName, 'green');
if (CLI::getOption('env')) {
CLI::write('Environment: ' . ENVIRONMENT);
}
$this->call('migrate:status');
}
}Spark CLI Reference
# Generators
php spark make:controller Products
php spark make:model ProductModel
php spark make:entity Product
php spark make:filter AuthFilter
php spark make:migration CreateProducts
php spark make:seeder ProductSeeder
php spark make:cell AlertMessageCell
php spark make:command AppInfo
php spark make:validation ProductRules
# Database
php spark migrate
php spark migrate:rollback
php spark migrate:refresh
php spark migrate:status
php spark db:seed ProductSeeder
php spark db:table products
# Utilities
php spark serve
php spark serve --port 9000
php spark routes
php spark filter:check GET /
php spark cache:clear
php spark logs:clear
php spark key:generate
php spark namespaces
php spark phpini:checkTesting
Setup:
composer require --dev phpunit/phpunit
vendor/bin/phpunitUnit test:
<?php
namespace Tests\App\Models;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
class ProductModelTest extends CIUnitTestCase
{
use DatabaseTestTrait;
protected $seed = 'Tests\Support\Database\Seeds\ProductSeeder';
public function testFindReturnsProduct()
{
$model = new \App\Models\ProductModel();
$product = $model->find(1);
$this->assertIsArray($product);
$this->assertSame('Widget A', $product['name']);
}
}Feature test (HTTP):
<?php
namespace Tests\App\Controllers;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\DatabaseTestTrait;
class ProductsTest extends CIUnitTestCase
{
use FeatureTestTrait, DatabaseTestTrait;
public function testIndexReturns200()
{
$result = $this->get('/products');
$result->assertStatus(200);
$result->assertSee('Products');
}
public function testApiReturnsJson()
{
$result = $this->withHeaders(['Accept' => 'application/json'])->get('/api/products');
$result->assertStatus(200);
$result->assertJSONFragment(['name' => 'Widget A']);
}
public function testCreateWithSession()
{
$result = $this->withSession(['logged_in' => true, 'user_id' => 1])
->withBodyFormat('json')
->post('/api/products', ['name' => 'New Product', 'price' => 29.99]);
$result->assertStatus(201);
}
}Controller test:
use CodeIgniter\Test\ControllerTestTrait;
class ProductsControllerTest extends CIUnitTestCase
{
use ControllerTestTrait;
public function testShowReturns404ForMissing()
{
$result = $this->controller(\App\Controllers\Products::class)->execute('show', 99999);
$this->assertFalse($result->isOK());
}
}CI Shield Authentication
composer require codeigniter4/shield
php spark shield:setup
php spark migrate// Route protection
$routes->group('', ['filter' => 'session'], function ($routes) {
$routes->get('dashboard', 'Dashboard::index');
});
$routes->group('api', ['filter' => 'tokens'], function ($routes) {
$routes->resource('products');
});
// In controllers
$user = auth()->user();
if (auth()->loggedIn()) { /* authenticated */ }
if ($user->inGroup('admin')) { /* admin */ }
if ($user->can('products.edit')) { /* has permission */ }Content Negotiation
public function getData()
{
$data = model('ProductModel')->findAll();
$format = $this->request->negotiate('media', ['application/json', 'application/xml', 'text/html']);
return match ($format) {
'application/json' => $this->response->setJSON($data),
'application/xml' => $this->response->setXML($data),
default => view('products/index', ['products' => $data]),
};
}Logging & Error Handling
// PSR-3 levels: emergency, alert, critical, error, warning, notice, info, debug
log_message('error', 'Payment failed for order {id}', ['id' => $order_id]);
log_message('info', 'User logged in: {email}', ['email' => $user->email]);
// Custom exception views: app/Views/errors/html/error_404.php, error_exception.php
// HTTP exceptions:
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Product not found');Environment Config
# .env
CI_ENVIRONMENT = development
app.baseURL = 'http://localhost:8080/'
database.default.hostname = localhost
database.default.database = myapp
database.default.username = root
database.default.password = secret
database.default.DBDriver = MySQLi
encryption.key = hex2bin:your-key-hereNever commit .env. Set CI_ENVIRONMENT = production on production servers.
Common CI4 Pitfalls
1. Missing `$allowedFields`: Insert/update silently drops fields not listed. 2. Namespace mismatches: Controller namespace must match directory structure under app/. 3. `.env` not copied: CI4 ships .env.example — copy to .env and configure. 4. `public/` not set as web root: Server must point to public/, not project root. 5. CSRF on API routes: Disable CSRF for API endpoints in Filters.php. 6. `writable/` permissions: Must be writable by the web server. 7. Returning vs echoing: CI4 expects return view(...) — don't echo directly. 8. Double validation: Model's $validationRules + controller's $this->validate() = validating twice. Pick one. 9. `getPost()` vs `getJSON()`: Forms use getPost(), JSON APIs use getJSON(true). 10. Shield filter names: Use 'session' for web auth, 'tokens' for API — not 'auth'.
Deployment & Migration
Server configuration, production hardening, and the complete CI3 → CI4 migration reference.
Server Configuration
Apache (.htaccess)
CI3 — place in project root:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]CI4 — the public/ directory includes this by default. Ensure AllowOverride All is set in Apache config.
Nginx
CI3:
server {
listen 80;
server_name example.com;
root /var/www/project;
index index.php;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\. { deny all; }
}CI4 — same but set root /var/www/project/public;
Production Deployment Checklist
- [ ] Set
CI_ENVIRONMENT = productionin.env(CI4) orENVIRONMENTconstant inindex.php(CI3) - [ ] Point web root to
public/(CI4) — never expose project root - [ ]
writable/directory:chmod -R 775, owned by web server user - [ ] Remove
public/index.phpdebug toolbar references if present - [ ] Disable
display_errorsinphp.ini - [ ] Set
database.default.DBDebug = falsein production.env - [ ] Enable OPcache (
opcache.enable=1) - [ ] Configure production cache driver (Redis/Memcached instead of file)
- [ ] Set
session.cookie_secure = trueandsession.cookie_httponly = true - [ ] Run
php spark cache:clearafter deploy - [ ] Use
composer install --no-dev --optimize-autoloaderfor production
CI3 → CI4 Full Migration Reference
| CI3 | CI4 |
|---|---|
$this->load->model('x') | model('XModel') or DI |
$this->load->view('x', $data) | return view('x', $data) |
$this->load->library('x') | service('x') or new X() |
$this->load->helper('x') | helper('x') |
$this->input->post('x') | $this->request->getPost('x') |
$this->input->get('x') | $this->request->getGet('x') |
$this->input->post('x', TRUE) | $this->request->getPost('x') (no XSS param — use esc() in views) |
$this->db->get('table') | $db->table('table')->get() |
$query->result() | $query->getResult() |
$query->row() | $query->getRow() |
$query->result_array() | $query->getResultArray() |
$query->num_rows() | $query->getNumRows() |
$this->db->insert_id() | $db->insertID() |
$this->db->affected_rows() | $db->affectedRows() |
$this->db->count_all_results() | $builder->countAllResults() |
$this->db->trans_start() | $db->transStart() |
$this->db->trans_complete() | $db->transComplete() |
redirect('url') | return redirect()->to('url') |
show_404() | throw PageNotFoundException::forPageNotFound() |
show_error($msg) | throw new \RuntimeException($msg) |
$this->session->userdata('x') | session()->get('x') |
$this->session->set_userdata('k', $v) | session()->set('k', $v) |
$this->session->set_flashdata('k', $v) | session()->setFlashdata('k', $v) |
$this->session->flashdata('k') | session()->getFlashdata('k') |
html_escape($x) | esc($x) |
$this->upload->do_upload('f') | $this->request->getFile('f')->move(...) |
$this->email->send() | service('email')->send() |
$this->cache->get('k') | service('cache')->get('k') |
$this->pagination->create_links() | $model->pager->links() |
log_message('error', $msg) | log_message('error', $msg) (same API) |
$route['x'] = 'y' | $routes->get('x', 'Y::method') |
$route['default_controller'] | $routes->get('/', 'Home::index') |
Hooks ($hook[]) | Filters (middleware) |
CI_Controller | BaseController |
CI_Model | CodeIgniter\Model |
| No namespaces | PSR-4 namespaces |
| No CLI generator | php spark make:* |
| No built-in testing | PHPUnit + CIUnitTestCase |
| Ion Auth / Community libs | CI Shield (official) |
$config arrays in config/*.php | Classes in app/Config/*.php + .env |
application/ | app/ |
index.php in root | index.php in public/ |