# Case Study: CMMSchool — CodeIgniter 3 to CodeIgniter 4 Migration

---

## Project Overview

| Field              | Details                                      |
|--------------------|----------------------------------------------|
| **Project Name**   | CMMSchool Management System — CI4 Upgrade    |
| **Project Type**   | Framework Migration & Modernisation          |
| **Legacy Stack**   | CodeIgniter 3, PHP 5.x/7.x, MySQL            |
| **Upgraded Stack** | CodeIgniter 4, PHP 8.4, MySQL                |
| **Total Duration** | 2 Weeks                                      |
| **Delivery**       | Production-ready CI4 application             |

---

## Client Background

CMMSchool is a **Montessori-focused school operations platform** that serves multiple schools, managing the full lifecycle of school administration — from student enrollment and classroom management to teacher workflows, parent communications, and online payment processing.

The system supports three distinct user groups:

- **Administrators & School Owners** — full back-office control over schools, users, students, teachers, enrollments, and financials.
- **Teachers** — daily classroom workflows, lesson planning (Quests), rosters, check-in/out, assessments, and messaging.
- **Parents** — enrollment portal, fee payments via Stripe, student progress, and direct communication with staff.

---

## The Challenge

The client's existing application was built on **CodeIgniter 3** — a framework that had reached end-of-life, leaving the application exposed to:

- **Security vulnerabilities** from an unmaintained framework.
- **PHP 8.x incompatibilities** — CI3 is not compatible with modern PHP versions, blocking server upgrades.
- **Technical debt** — legacy patterns (`$this->load->model`, `$this->input->post`, `$this->session->flashdata`) spread across 130+ models and 30+ controllers.
- **Scalability concerns** — no namespacing, no PSR-4 autoloading, no dependency injection.
- **Maintenance risk** — future developers facing an outdated, unsupported codebase.

The application was large and mission-critical — it could not be rewritten from scratch. A **surgical, zero-data-loss migration** was required.

---

## Scope of Work

### Module Inventory

The application contained **3 major module groups** spanning over **30 controllers** and **219 view files**:

#### Admin Module
Full back-office for school administrators and school owners.

| Sub-module         | Functionality                                              |
|--------------------|------------------------------------------------------------|
| Dashboard          | School-wide KPIs and activity overview                     |
| Schools            | Multi-school management                                    |
| Users              | Role-based user accounts and access control                |
| Students           | Student records, siblings, forms, withdrawals              |
| Teachers           | Teacher profiles, schedules, class assignments             |
| Classrooms         | Room management, programs, activity schedules              |
| Enrollment         | Registration pipeline and status tracking                  |
| Prospects          | Prospect tracking, tour requests, conversion pipeline      |
| Class Roster       | Roster reports, future class assignments                   |
| Activities         | School activities and program linking                      |
| Events             | Calendar event management with sync                        |
| Parent Concerns    | Concern logging, categorisation, and resolution            |
| Internal Messages  | Staff-to-staff internal messaging with attachments         |
| Teacher Messages   | Teacher-facing message threads with webcam support         |
| Email Templates    | Configurable email templates for automated communications  |
| Portals            | Announcements, newsletters, documents, and notifications   |
| Requests           | Support and operational request tracking                   |
| Withdrawals        | Student withdrawal processing and records                  |

#### TP Module (Teacher / Parent Portal)
Dedicated portal for teachers and parents.

| Sub-module         | Functionality                                              |
|--------------------|------------------------------------------------------------|
| Teacher Auth       | Login, logout, forgot/reset password                       |
| Unified Role (UR)  | School/class selection, role-based dashboard               |
| Parent Auth (PA)   | Parent login, password reset                               |
| Parent Portal (PP) | Iframe-capable login, parent dashboard, class access       |
| Rosters            | Daily check-in / check-out with timestamps                 |
| Quests             | Montessori lesson planning, record-keeping, assignments    |
| Reports            | Daily activity and progress reports                        |
| Student Assessment | Baseline assessments, Montessori RA record-keeping         |
| Student Enrollment | Registration flow, AJAX student list, Stripe handoff       |
| Payment            | Stripe Checkout for enrollment fees                        |
| Internal Messages  | Parent/teacher internal messaging                          |
| Teacher Messages   | Teacher-to-teacher messaging with webcam attachments       |
| Incoming           | Incoming notification feeds                                |

#### Public / Utility
| Controller             | Functionality                                          |
|------------------------|--------------------------------------------------------|
| Home                   | Public landing, redirects to login                    |
| RegistrationPaperForm  | PDF registration form serving                         |
| Stripe Webhook         | `checkout.session.completed` payment finalisation     |

---

### Database Scale

The migrated database schema contained **127+ tables** across all functional domains:

| Domain                        | Tables (count) |
|-------------------------------|----------------|
| Users, Roles & Access Control | 12             |
| Schools & Staff               | 3              |
| Academic Structure            | 12             |
| Student Management            | 13             |
| Teacher Management            | 5              |
| Activities & Scheduling       | 7              |
| Montessori RA Assessments     | 5              |
| Baseline Assessments (BA)     | 5              |
| Student Development Records   | 5              |
| Enrollment & Prospects        | 8              |
| Parents & Family              | 4              |
| Concerns & Behaviour          | 3              |
| Messaging & Communication     | 8              |
| Announcements & Notifications | 5              |
| Payments & Finance            | 5              |
| Events & Calendar             | 2              |
| Email & Automation            | 2              |
| Reference / Lookup Data       | 17             |
| Miscellaneous                 | 6              |

---

## Solution Approach

### Phase 1 — Migration (Week 1)

**Goal:** Convert the entire CI3 codebase to CI4-compatible architecture without altering business logic or database schema.

#### Key Technical Conversions

| CI3 Pattern                             | CI4 Equivalent                                      |
|-----------------------------------------|-----------------------------------------------------|
| `$this->load->model('securities')`      | `model(SecuritiesModel::class)`                     |
| `$this->load->view('x', $data)`         | `return view('x', $data)`                           |
| `$this->input->post('x')`              | `$this->request->getPost('x')`                      |
| `$this->config->item('base_url')`      | `base_url()`                                        |
| `$this->session->set_userdata('k','v')`| `session()->set('k', 'v')`                          |
| `$this->session->flashdata('k')`       | `session()->getFlashdata('k')`                      |
| `redirect(base_url().'path')`          | `return redirect()->to(base_url('path'))`           |
| Global constants (`TEACHER_ROLE_ID`)   | `CmmConstants::TEACHER_ROLE_ID`                     |
| `$this->securities->AllowedRoles(…)`   | `$this->securitiesModel->allowedRoles(…)`           |
| jQuery `$.get()` / `$.ajax()`          | Native `fetch()` API                                |
| `form_error()` / `set_value()`         | `old()` + CI4 validation error passing              |

#### What Was Migrated

- **131+ Models** — all domain models namespaced under `App\Models`, PSR-4 autoloaded.
- **30+ Controllers** — fully namespaced (`App\Controllers\Admin\*`, `App\Controllers\Tp\*`), using CI4 request/response lifecycle.
- **219 View files** — converted from CI3 loader syntax to CI4 `view()` helpers.
- **Routes** — all routes registered explicitly in `app/Config/Routes.php`.
- **Config classes** — environment-driven via `.env` (Database, Stripe, Email, App).
- **Session** — migrated to CI4 database-backed session handler.
- **Security model** — CSRF protection, input sanitisation, role-based access guards ported to CI4 Filters.
- **Stripe integration** — rebuilt using `stripe/stripe-php ^16` with Checkout Sessions, Payment Intents, and signed Webhook verification.

---

### Phase 2 — Testing & UI Fixes (Week 1)

**Goal:** Validate all migrated functionality end-to-end, resolve regressions, align UI behaviour, and ensure form validation parity.

#### Testing Coverage

- **Feature tests** — HTTP-level tests for all major routes (admin, TP, payment, enrollment).
- **Database tests** — integration tests against a real test database (not mocked).
- **Webhook tests** — Stripe `checkout.session.completed` event processing validated end-to-end.
- **Guest route tests** — verified all unauthenticated access is correctly redirected.
- **Validation tests** — all form validation rules tested for correct pass/fail behaviour.

#### Test files delivered

| Test File                          | Coverage Area                              |
|------------------------------------|--------------------------------------------|
| `AdminHomeFeatureTest`             | Admin dashboard authentication & access    |
| `AdminModulesGuestFeatureTest`     | Admin module guest-access protection       |
| `TpGuestFeatureTest`               | TP portal unauthenticated route handling   |
| `TpLoginValidationFeatureTest`     | Teacher/parent login validation rules      |
| `TpPaymentGuestFeatureTest`        | Payment flow guest-access protection       |
| `RegistrationPaperFormFeatureTest` | PDF registration form serving              |
| `RouteInventoryGuestTest`          | Full route inventory guest-access sweep    |
| `NotFoundFeatureTest`              | 404 handler and custom error page          |
| `ExampleDatabaseTest`              | Database connectivity and query baseline   |

#### UI & Bug Fixes

- Form validation error display aligned with CI4 `validation->getError()` output.
- Flash message rendering corrected across all login/logout flows.
- `old()` helper used consistently for form field repopulation after validation failure.
- AJAX endpoints updated from jQuery `$.get`/`$.post` to native `fetch()` with JSON responses.
- Stripe Checkout redirect and webhook callback flows verified in test mode.
- 404 and error pages wired to CI4's custom error handler (`My404`).

---

## Technology Stack Delivered

### Backend

| Layer              | Technology                        | Version     |
|--------------------|-----------------------------------|-------------|
| Language           | PHP                               | 8.4         |
| Framework          | CodeIgniter 4                     | ^4.0        |
| Database           | MySQL (via CI4 Query Builder)     | —           |
| ORM / Query Layer  | CI4 Model + Query Builder         | —           |
| Payment Processing | Stripe PHP SDK                    | ^16.0       |
| Spreadsheet Export | PhpSpreadsheet                    | ^5.5        |
| Session Storage    | Database-backed (CI4)             | —           |
| Autoloading        | PSR-4 via Composer                | —           |

### Dev & Testing

| Tool               | Purpose                           | Version     |
|--------------------|-----------------------------------|-------------|
| PHPUnit            | Unit & feature test runner        | ^10.5       |
| Faker PHP          | Seed and test data generation     | ^1.9        |
| vfsStream          | Virtual filesystem for tests      | ^1.6        |
| Composer           | Dependency management             | —           |

### Frontend

| Library / Framework    | Purpose                              |
|------------------------|--------------------------------------|
| Bootstrap 3            | Core UI grid and components          |
| ACE Admin Theme        | Admin panel UI skin                  |
| Font Awesome 4.7       | Icon set                             |
| jQuery                 | DOM manipulation                     |
| jQuery DataTables      | Server-side sortable/paginated tables|
| jQuery Validate        | Client-side form validation          |
| jQuery UI 1.10.3       | Date pickers, widgets                |
| FullCalendar           | Event calendar (daygrid, timegrid)   |
| Moment.js              | Date/time parsing and formatting     |
| Chosen.js              | Enhanced select dropdowns            |
| DateRangePicker        | Date range inputs                    |
| Bootstrap Timepicker   | Time inputs                          |
| Bootbox.js             | Alert/confirm/prompt dialogs         |
| Bootstrap WYSIWYG      | Rich text editing                    |
| jQuery Multiple Select | Multi-select dropdowns               |
| Flot / Sparkline       | Charts and inline graphs             |
| jQuery Sidr            | Sidebar navigation                   |
| Mustache / Hogan.js    | Client-side templating               |

### Third-Party Integrations

| Service        | Integration Method                                            |
|----------------|---------------------------------------------------------------|
| **Stripe**     | PHP SDK — Checkout Sessions, Payment Intents, Signed Webhooks |
| **SMTP Email** | CI4 Email service — configurable via `.env`                   |
| **Google**     | Google Calendar OAuth (auth structure preserved for migration) |

---

## Project Timeline

| Phase              | Duration | Key Deliverables                                                                      |
|--------------------|----------|---------------------------------------------------------------------------------------|
| **Migration**      | 1 Week   | All controllers, models, views, routes, config ported from CI3 → CI4                 |
| **Testing & UI Fixes** | 1 Week | Full test suite, bug fixes, validation alignment, Stripe end-to-end verification |
| **Total**          | **2 Weeks** | Production-ready CI4 application                                                 |

---

## Results & Outcomes

| Metric                        | Outcome                                                         |
|-------------------------------|-----------------------------------------------------------------|
| Framework                     | CI3 (EOL) → CI4 (actively maintained, PHP 8.x native)          |
| PHP Version Compatibility     | Fully compatible with PHP 8.4                                   |
| Models migrated               | 131+                                                            |
| Controllers migrated          | 30+                                                             |
| Views converted               | 219                                                             |
| Database tables               | 127+ (zero schema changes — full backward compatibility)        |
| Test coverage                 | 9 feature/integration test files covering all major flows       |
| Stripe integration            | Rebuilt with SDK v16, Checkout + Webhooks, test mode verified   |
| Security posture              | CSRF protection, signed webhooks, input sanitisation, CI4 Filters |
| Data loss                     | None — existing MySQL schema preserved throughout               |

---

## Key Technical Highlights

**Zero-downtime schema strategy** — The migration maintained full database compatibility with the legacy CI3 system. No tables were renamed, no columns were altered, ensuring a safe rollback window during transition.

**Business logic preserved** — All controller and model logic was carried over verbatim; only the framework interaction layer (loaders, session access, request input) was converted to CI4 APIs.

**Modern PHP practices introduced** — PSR-4 namespacing, constructor injection, CI4 Filters for authentication guards, and environment-driven configuration replaced hardcoded legacy patterns.

**Stripe rebuild** — The payment integration was fully rebuilt from legacy CI3 Charges to modern Stripe Checkout Sessions with server-side webhook signature verification — aligned with Stripe's current best practices.

**Test suite established** — A PHPUnit test suite was introduced from scratch, covering feature-level HTTP tests, guest-access protection, form validation, database connectivity, and payment webhook handling.

---

## Conclusion

The CMMSchool CI3 → CI4 migration was completed in **2 weeks**, delivering a fully modernised, production-ready school management platform. The client now operates on a supported, actively maintained framework with PHP 8.4 compatibility, a comprehensive test suite, modern Stripe payment integration, and a clean codebase ready for future feature development.

---

*Document prepared for CMMSchool project — CI4 Upgrade engagement.*
