Good habits keep CodeIgniter projects clean, secure and fast.
Structure
- Define every route in
Routes.php; keep auto routing off - Keep controllers thin: database code in models, reusable logic in libraries or services
- Group admin code in
Controllers/Adminand protect it with a filter - Use migrations for every table change and seeders for starting data
- Put shared helpers in
BaseController::$helpers
Security
- Enable the csrf filter; use
csrf_field()in all forms - Print with
esc()everywhere - Validate all input; set
$allowedFieldson models password_hash()for passwords;session()->regenerate()after loginCI_ENVIRONMENT = productionand HTTPS on the live site;.envnever in Git
Performance
- Paginate long lists; select only needed columns
- Add database indexes on searched columns
- Cache data that rarely changes
- Avoid queries inside loops — use joins or
whereIn()
Quality
- Follow PSR-12 code style
- Read
writable/logsregularly - Write tests for important features
- Read the official guide at codeigniter.com/user_guide
Example
Example — Before and after: avoid queries in a loop
PHP
<?php
// ❌ Before: one extra query for every post (N+1)
$posts = model('PostModel')->findAll();
foreach ($posts as &$post) {
$post['author'] = model('UserModel')->find($post['user_id'])['name'];
}
// ✅ After: one query with a join, only needed columns, paginated
$model = model('PostModel');
$posts = $model->select('posts.id, posts.title, posts.slug, users.name AS author')
->join('users', 'users.id = posts.user_id')
->where('posts.status', 'published')
->orderBy('posts.id', 'DESC')
->paginate(12);
return view('posts/index', ['posts' => $posts, 'pager' => $model->pager]);
The first version runs 1 + (number of posts) queries. The second runs one query (plus a count for pagination) and loads only 12 rows.