Explain MVC Architecture in CodeIgniter
MVC stands for Model–View–Controller. It is a software design pattern used in CodeIgniter to divide an application into three separate components, with each component having a specific responsibility.
MVC separates business logic, presentation, and user requests, making the application easier to develop, understand, maintain, and modify.
MVC Architecture
User / Browser
|
| HTTP Request
↓
┌─────────────┐
│ Controller │
└─────────────┘
/ \
/ \
↓ ↓
┌─────────────┐ ┌─────────────┐
│ Model │ │ View │
└─────────────┘ └─────────────┘
| |
↓ ↓
Database Web Page/UI
The Model represents the data structure of the application. It generally contains functions for retrieving, inserting, and updating data, and working with application data. Thus, the Model mainly handles data and database-related operations.
class StudentModel extends Model
{
public function getStudents()
{
return $this->findAll();
}
}
The View represents the information presented to the user. It is normally a web page containing HTML, but it can also be a page fragment such as a header or footer, or other types of pages. The View is mainly responsible for the presentation/user interface.
<h2>Student Details</h2>
<p>Name: Rahul</p>
<p>Course: BCA</p>
The Controller acts as an intermediary between the Model, View, and other resources required to process an HTTP request and generate a web page. It receives the user's request, communicates with the Model when data is required, and then sends the appropriate data to the View.
class Student extends BaseController
{
public function index()
{
$model = new StudentModel();
$data['students'] = $model->getStudents();
return view('students', $data);
}
}
Working of MVC
User Request → Controller → Model → Database
Model → Controller → View → Response to User
For example, when a user requests a student page:
Step 1: The Controller receives the request.
Step 2: The Controller asks the Model for student data.
Step 3: The Model retrieves the data from the database.
Step 4: The Model returns the data to the Controller.
Step 5: The Controller passes the data to the View.
Step 6: The View displays the student information to the user.
Advantages of MVC
Explain URL Routing in CodeIgniter
URL Routing is the process of connecting a URL requested by the user to a specific controller and its method in a CodeIgniter application.
URL → Route → Controller → Method → Response
For example, when the user visits http://localhost/myproject/course, CodeIgniter checks the defined routes and determines which controller method should execute: /course → Course Controller → index().
What is a Route?
A route defines which controller method should be executed when a particular URL is requested. In CodeIgniter 4, routes are generally defined in app/Config/Routes.php.
$routes->get('/course', 'Course::index');
This means /course is the URL, Course is the Controller, index is the Controller method, and get() represents an HTTP GET request.
Types of Routing in CodeIgniter 4
In Defined Route Routing, the developer manually specifies the URL and the corresponding controller method.
$routes->get('/course', 'Course::index');
When /course is requested, CodeIgniter executes the index() method of the Course controller.
Advantages: provides more control over URLs; URLs can be customized; provides better security; only explicitly defined routes are available.
In Auto Routing, CodeIgniter automatically determines the controller and method from the requested URL according to its routing conventions. There is no need to manually define every route.
/course/index
↓
Course::index()
Example of Routes.php
<?php
use CodeIgniter\Router\RouteCollection;
$routes->get('/', 'Home::index');
$routes->get('course', 'Course::index');
$routes->post('course/save', 'Course::save');
| URL | Controller | Method | Request |
|---|---|---|---|
| / | Home | index() | GET |
| /course | Course | index() | GET |
| /course/save | Course | save() | POST |
For example, $routes->post('course/save', 'Course::save'); means that when a form sends data to /course/save using POST, CodeIgniter executes the save() method of the Course controller.
Default Controller and Default Route
The default controller is the controller loaded when the user visits the application's base URL without specifying a controller. For example, http://localhost/myproject/ can execute Home::index().
The default route is normally defined in app/Config/Routes.php:
$routes->get('/', 'Home::index');
Here / represents the root URL, Home is the controller, and index is the method.
Explain MySQLi or PDO (Database Connection) in CodeIgniter
PHP provides two main extensions for connecting with MySQL databases: MySQLi (MySQL Improved) and PDO (PHP Data Objects). Both can be used to connect PHP applications with databases and support prepared statements, which help protect applications from SQL injection.
MySQLi stands for MySQL Improved. It is a PHP extension used to connect specifically with MySQL databases.
Features: works with MySQL databases; easy to use; supports Object-Oriented and Procedural programming styles; supports prepared statements; provides good performance for MySQL applications.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "ComplaintDB";
$conn = new mysqli($host, $user, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Database connected successfully";
?>
Here, new mysqli() creates a connection between PHP and the MySQL database.
PDO stands for PHP Data Objects. It is a database access layer that allows PHP to connect with different types of databases using a similar programming style. PDO supports databases such as MySQL, PostgreSQL, SQLite, Oracle, and SQL Server.
<?php
$host = "localhost";
$db = "ComplaintDB";
$user = "root";
$password = "";
$conn = new PDO(
"mysql:host=$host;dbname=$db",
$user,
$password
);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database connected successfully";
?>
MySQLi vs PDO
| Feature | MySQLi | PDO |
|---|---|---|
| Database Support | Only MySQL | Multiple databases |
| Programming Style | Object-oriented and procedural | Object-oriented |
| Prepared Statements | Supported | Supported |
| Portability | Less portable | More portable |
| Ease of Use | Easy to learn | Slightly advanced |
| Database Switching | Difficult | Easier |
Database Connection in CodeIgniter
CodeIgniter provides a database layer so that the Model can connect to the database and perform operations such as findAll() (retrieve all records), find() (retrieve a record), insert() (insert data), update() (update data), and delete() (delete data). For example:
<?php
namespace App\Models;
use CodeIgniter\Model;
class CourseModel extends Model
{
protected $table = 'course';
protected $primaryKey = 'Id';
protected $allowedFields = ['Id', 'Name'];
protected $returnType = 'array';
}
The CodeIgniter Model provides these built-in database functions and works with the specified course table.
Working
Controller
↓
Model
↓
Database
↓
Model
↓
Controller
↓
View
For example, the Controller can create a CourseModel object and use:
$model = new CourseModel();
$data['courses'] = $model->findAll();
return view('course_form', $data);
Here, findAll() retrieves the course records from the database and the Controller sends them to the View.
How to Use/Manage Session and Flash Data in CodeIgniter?
Session in CodeIgniter is used to store user data across multiple requests. It can be used for information such as user ID, username, and login status.
Flashdata is a special type of session data that is stored temporarily and is automatically removed after it is used. It is commonly used for success and error messages.
Setting Session Data — session data can be stored using:
session()->set([
'username' => 'Rahul',
'user_id' => 101
]);
Getting Session Data — to retrieve stored session data:
$username = session()->get('username');
Removing Session Data — a particular session value can be removed using:
session()->remove('username');
Flashdata is used when information is required only temporarily, generally for the next request — for example, displaying "Registration successful." after a successful registration.
Setting Flashdata:
session()->setFlashdata(
'message',
'Registration successful!'
);
Retrieving Flashdata:
$message = session()->getFlashdata('message');
After it has been used, the flashdata automatically expires.
Difference Between Session and Flashdata
| Feature | Session | Flashdata |
|---|---|---|
| Purpose | Stores data for multiple requests | Stores temporary data |
| Lifetime | Remains until manually removed or session ends | Automatically removed after use |
| Examples | User ID, username, login status | Success/error messages |
| Set Method | session()->set() | session()->setFlashdata() |
| Get Method | session()->get() | session()->getFlashdata() |
| Removal | session()->remove() | Automatically expires |
Example
// Store user information
session()->set('username', 'Rahul');
// Retrieve user information
$username = session()->get('username');
// Store temporary success message
session()->setFlashdata(
'message',
'Data saved successfully!'
);
// Retrieve temporary message
$message = session()->getFlashdata('message');
Explain File Management in CodeIgniter with Examples
File management in CodeIgniter refers to handling files uploaded by users, such as images, documents, and other files. CodeIgniter provides the $this->request object and an UploadedFile object to obtain and manage uploaded files.
A common approach is to create an upload folder inside the project's public directory, for example public/Uploads/.
Steps for File Upload
Create the following folder in the CodeIgniter project:
public/Uploads/
Example:
C:\xampp\htdocs\codeigniter4-framework\public\Uploads
The uploaded file can be obtained using:
$file = $this->request->getFile('myfile');
Here, myfile is the name of the file input in the HTML form.
if ($file->isValid()) {
// File is valid
}
The isValid() method checks whether the uploaded file is valid.
CodeIgniter can generate a random file name using:
$newName = $file->getRandomName();
This is useful to avoid conflicts between files having the same name.
The file can then be moved to the upload directory:
$file->move('public/Uploads', $newName);
The move() method moves the uploaded file to the specified destination.
Complete Example
HTML Form
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
Controller
public function upload()
{
$file = $this->request->getFile('myfile');
if ($file->isValid()) {
$newName = $file->getRandomName();
$file->move('public/Uploads', $newName);
return "File uploaded successfully";
}
return "File upload failed";
}
Important File Management Methods
| Method | Purpose |
|---|---|
| $this->request->getFile('myfile') | Gets the uploaded file |
| $file->isValid() | Checks whether the upload is valid |
| $file->hasMoved() | Checks whether the file has already been moved |
| $file->getName() | Gets the file name |
| $file->getRandomName() | Generates a random file name |
| $file->getClientName() | Gets the original client file name |
| $file->getClientExtension() | Gets the file extension |
| $file->getSize() | Gets the file size |
| $file->move() | Moves the file to the destination |
Explain the Use of Helpers and Libraries in CodeIgniter
CodeIgniter provides Helpers and Libraries to simplify common web-development tasks. They provide reusable functionality so that developers do not have to write the same code repeatedly.
A Helper is a collection of simple functions designed to perform tasks of a particular category. Helpers are procedural functions, not classes or objects. Each helper function generally performs a specific task.
Common helpers: URL Helper — helps in creating URLs and links; Form Helper — helps in creating form elements; Text Helper — provides text formatting functions; Cookie Helper — helps set and read cookies; Filesystem Helper — provides functions for working with files.
A helper can be loaded using:
helper('url');
After loading the URL Helper, its functions can be used for URL-related operations.
A Library generally provides a class or service containing more complex functionality than a helper. In CodeIgniter 4, many libraries are accessed using the service() function.
Example: Validation Library
$validation = \Config\Services::validation();
$validation->setRules([
'name' => 'required',
'email' => 'required|valid_email'
]);
Here, the validation service provides functionality for checking whether form data satisfies the specified rules.
Difference Between Helpers and Libraries
| Feature | Helpers | Libraries |
|---|---|---|
| Structure | Collection of functions | Class/service |
| Programming style | Procedural | Object-oriented |
| Complexity | Used for simple tasks | Used for more complex functionality |
| Example | URL Helper, Form Helper | Validation Library |
| Loading | helper('url') | service() / CodeIgniter service |