Web Framework and Services — Study Notes

Unit 03

MVC Architecture, URL Routing, Database Connectivity, Sessions & Flashdata, File Management, Helpers & Libraries in CodeIgniter

6 Questions 5 Marks Each Web Framework and Services
01
5 Marks Question

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
01
Model

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();
    }
}
02
View

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>
03
Controller

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

Separation of concerns
Data, presentation, and request handling are separated.
Easy maintenance
Changes in one part have less effect on other parts.
Code reusability
Models and other components can be reused.
Easy development
Different parts of the application can be developed separately.
Better organization
Large applications become easier to understand and manage.
Conclusion CodeIgniter's MVC architecture divides an application into Model, View, and Controller. The Model handles data, the View handles presentation, and the Controller processes requests and coordinates between them. This separation makes CodeIgniter applications more organized, maintainable, and easier to modify.
02
5 Marks Question

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

01
Defined Route Routing

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.

02
Auto Routing

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
/Homeindex()GET
/courseCourseindex()GET
/course/saveCoursesave()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.

Conclusion URL routing in CodeIgniter provides a connection between user requests and application logic. It maps URLs to specific controller methods and can be implemented using Defined Routes or Auto Routing. Routes are generally configured in app/Config/Routes.php, making URL handling organized and controllable.
03
5 Marks Question

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.

Note: In CodeIgniter, database operations are normally handled through its Model and database layer, rather than creating a raw MySQLi/PDO connection in every controller. The notes first explain MySQLi/PDO as PHP database connection methods and then show CodeIgniter Models using built-in database functions.
01
MySQLi

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.

02
PDO

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 SupportOnly MySQLMultiple databases
Programming StyleObject-oriented and proceduralObject-oriented
Prepared StatementsSupportedSupported
PortabilityLess portableMore portable
Ease of UseEasy to learnSlightly advanced
Database SwitchingDifficultEasier

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.

Conclusion MySQLi and PDO are PHP methods for database connectivity. MySQLi is specifically designed for MySQL, while PDO supports multiple databases and is more portable. In CodeIgniter, database interaction is organized through the Model, which provides built-in methods for performing CRUD operations on the database.
04
5 Marks Question

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.

01
Session Management

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');
02
Flashdata

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
PurposeStores data for multiple requestsStores temporary data
LifetimeRemains until manually removed or session endsAutomatically removed after use
ExamplesUser ID, username, login statusSuccess/error messages
Set Methodsession()->set()session()->setFlashdata()
Get Methodsession()->get()session()->getFlashdata()
Removalsession()->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');
Conclusion CodeIgniter provides session management for maintaining user-related information across requests. Normal session data is used for persistent information such as login status, while Flashdata is used for temporary messages such as success or error notifications.
05
5 Marks Question

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

01
Create Upload Folder

Create the following folder in the CodeIgniter project:

public/Uploads/

Example:
C:\xampp\htdocs\codeigniter4-framework\public\Uploads
02
Get the Uploaded File

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.

03
Check Whether the File is Valid
if ($file->isValid()) {
    // File is valid
}

The isValid() method checks whether the uploaded file is valid.

04
Generate a File Name

CodeIgniter can generate a random file name using:

$newName = $file->getRandomName();

This is useful to avoid conflicts between files having the same name.

05
Move the File

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
Conclusion CodeIgniter provides convenient methods for uploading and managing files. The uploaded file is obtained using getFile(), checked using isValid(), optionally given a random name using getRandomName(), and finally stored using move(). This makes file-upload handling simple and organized in CodeIgniter applications.
06
5 Marks Question

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.

01
Helpers

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.

02
Libraries / Services

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
StructureCollection of functionsClass/service
Programming styleProceduralObject-oriented
ComplexityUsed for simple tasksUsed for more complex functionality
ExampleURL Helper, Form HelperValidation Library
Loadinghelper('url')service() / CodeIgniter service

Advantages

Code reusability
Common functionality can be reused.
Less coding
Developers don't need to implement common tasks from scratch.
Faster development
Ready-made functionality speeds up development.
Better organization
Related functionality is grouped together.
Simplifies complex tasks
Libraries provide ready-made classes/services for advanced operations.
Conclusion Helpers and Libraries are reusable features provided by CodeIgniter. Helpers provide simple procedural functions for tasks such as URLs, forms, cookies, and files, while Libraries/Services provide more complex class-based functionality such as validation.