CodeIgniter
01 / 02

MVC, Routing & the Query Builder

CodeIgniter: MVC, Routing & the Query Builder

CodeIgniter is a lightweight PHP MVC framework known for a small footprint, minimal configuration, and low overhead compared to heavier frameworks like Laravel or Symfony. CodeIgniter 4 modernized the codebase (namespaces, PSR-4) while CI3 remains widely deployed in legacy projects.

Controllers & Default Routing

<?php
// app/Controllers/Articles.php
namespace App\Controllers;

use App\Models\ArticleModel;

class Articles extends BaseController
{
    public function view(int $id)
    {
        $model = new ArticleModel();
        $article = $model->find($id);

        if (!$article) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('articles/view', ['article' => $article]);
    }
}

// Default segment-based routing: /articles/view/5 maps to
// Articles::view(5) automatically, with zero explicit route config.
// app/Config/Routes.php overrides this for custom URL patterns:
$routes->get('/blog/(:num)', 'Articles::view/$1');
$routes->resource('articles'); // conventional CRUD routes

Models & Query Builder

<?php
// app/Models/ArticleModel.php
namespace App\Models;

use CodeIgniter\Model;

class ArticleModel extends Model
{
    protected $table = 'articles';
    protected $allowedFields = ['title', 'body', 'status'];
    protected $returnType = 'App\Entities\Article'; // optional Entity object

    protected $validationRules = [
        'title' => 'required|min_length[3]|max_length[255]',
    ];

    public function published()
    {
        return $this->where('status', 'published')->orderBy('created_at', 'DESC');
    }
}

// Query Builder -- fluent, chainable, parameterized (no raw string concat)
$db = \Config\Database::connect();
$builder = $db->table('articles');
$results = $builder->where('status', 'published')
    ->orderBy('created_at', 'DESC')
    ->get()
    ->getResult();

// Raw SQL is still available when needed
$db->query('SELECT * FROM articles WHERE id = ?', [$id]);

Views

<!-- app/Views/articles/view.php -- plain PHP templates, no separate templating language -->
<h1><?= esc($article->title) ?></h1>
<div><?= $article->body ?></div>

<?php foreach ($comments as $comment): ?>
  <p><?= esc($comment->text) ?></p>
<?php endforeach; ?>

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free