agyanadda@gmail.com

CodeIgniter 4 Best Practices

APIs and Advanced Topics 1 min read Updated Dec 3, 2026 Topic 30 of 30

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/Admin and 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 $allowedFields on models
  • password_hash() for passwords; session()->regenerate() after login
  • CI_ENVIRONMENT = production and HTTPS on the live site; .env never 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/logs regularly
  • 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Where should database code usually go?

Exercise 2 True / False

Auto routing should be kept off and routes defined explicitly.

Exercise 3 Fill in the Blank

Escape all output in views with ___()

Frequently Asked Questions

Start with a blog (posts, categories, comments, login), then a student management system with CRUD, search and pagination, then a small shop with cart, orders and a REST API. Each uses routing, models, validation, sessions, filters and file uploads.