Codeigniter

Using CodeIgniter MVC build a Scalable Web Application

Thu, 30.03.2023
Abidhusain Chidi
Co-Founder and CEO
Using CodeIgniter MVC build a Scalable Web Application

Popular open-source PHP web development framework CodeIgniter is a simple but effective toolbox for creating dynamic web applications. A lightweight and quick core, a wealth of libraries, a flexible routing system, and an intuitive Model-View-Controller (MVC) architecture are just a few of the things it provides. We’ll concentrate on the MVC architecture of CodeIgniter and its benefits for web development in this blog article.

I. Understanding the MVC architecture of CodeIgniter

One of the most popular design patterns in software development, especially for web development, is the Model-View-Controller (MVC) architecture. It offers a clear division of responsibilities between the many parts of an application, making it simpler to create, maintain, and grow. The three primary elements of CodeIgniter’s MVC implementation are:

  • Model: The Model symbolizes the application’s data layer. It is in charge of connecting with the database and carrying out CRUD activities (Create, Read, Update, Delete) on data. Models are often built in CodeIgniter as classes that extend the CI_Model class.
  • View: The View serves as the application’s display layer. It is in charge of producing the HTML, CSS, and JavaScript that the user sees. The basic implementation of Views in CodeIgniter is a PHP file that receives data from the Controller and renders it into HTML.
  • Controller: The controller serves as the application’s representation of the logic layer. It is in charge of dealing with user queries, processing data, and returning answers to the user. The most common way to build a controller in CodeIgniter is by using classes that extend the CI_Controller class.

There are several benefits to adopting MVC when developing websites. Developers may build cleaner, more modular code that is simpler to test and debug by breaking an application’s concerns into separate components. It also makes it simpler to alter an application’s behavior without impacting other areas of the code.

II. how to create a CodeIgniter MVC project

1. Installation and configuration guidelines:

You must download the most recent version of CodeIgniter from the official website (https://codeigniter.com/) before you can begin. After downloading the package, extract it to the document root directory of your web server.

2. Overview of the file structure:

A CodeIgniter MVC project’s file structure is made up of various folders and files, including:

  • app/: This directory contains the main application code, including the Controllers, Models, and Views.
  • system/: This directory contains the CodeIgniter core files.
  • public/: This directory contains public assets such as CSS, JavaScript, and images.
  • index.php: This is the entry point of the application.

3. Setting up a connection between CodeIgniter and the database:

You must establish a database and set up CodeIgniter to connect to it in order to utilize the Model in CodeIgniter to communicate with a database. To set up CodeIgniter and establish a database, adhere to these steps:

  • Create a new MySQL database.
  • Open “app/Config/Database.php” and edit the following lines to reflect the information from your database:
public $default = array(
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'your-username',
    'password' => 'your-password',
    'database' => 'your-database',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',

III. Establishing the Model

In CodeIgniter, connecting with the application’s database, querying it, and updating data are the responsibilities of a Model. The following describes how to construct a Model in CodeIgniter:

1. Choose a name for a new PHP file that you should create in the “application/models” directory. Take “User_model.php,” for instance.

2. Add an extension to the “CI_Model” class and define a class with the same name as the file.

class User_model extends CI_Model {
}

3. Define database operation-related functions within the class. To obtain all users from the database, for instance:

class User_model extends CI_Model {

    function get_users() {
        $query = $this->db->get('users');
        return $query->result();
    }
}

The database library that comes with CodeIgniter is used in the code above to obtain all of the users from the “users” table. An array of objects representing the rows the database returned are returned by the “result()” method.

Examples of common tasks a Model can perform:

  • Inserting data into the database
  • Updating data in the database
  • Retrieving data from the database based on certain criteria
  • Deleting data from the database

IV. Creating the View

The HTML output is rendered to the user using a view in CodeIgniter. To construct a View in CodeIgniter, follow these steps:

1. Choose a name for a new PHP file that you’ll create in the “application/views” directory. “Users.php,” as an example.

2. Write the HTML code for the view within the file. PHP code may also be used to dynamically create HTML output. For instance:

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <h1>Users</h1>
    <table>
      <head>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <body>
            <?php foreach ($users as $user): ?>
                <tr>
                    <td><?php echo $user->name; ?></td>
                    <td><?php echo $user->email; ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>

In the code above, each loop is used to traverse over the array of users that the Model supplied and create the HTML table rows on the fly.

Examples of common tasks a View can perform:

  • Displaying data retrieved from the Model
  • Rendering HTML forms for user input
  • Displaying error messages or success messages to the user

V. The Controller’s creation

Model-View-Controller (MVC) architecture is used by the popular PHP framework CodeIgniter. The Controller in MVC is in charge of handling user requests and returning the appropriate answer to the user. This section will cover the definition of a Controller in CodeIgniter, how to construct one, and some typical activities it can carry out.

CodeIgniter’s definition of a controller

A class called a Controller in CodeIgniter is in charge of processing and reacting to user requests. It includes methods that stand in for the various operations a user could carry out on the application. For instance, the Controller might include a function that passes the product data to the examine for display if a user wanted to examine a list of items on an e-commerce website.

In CodeIgniter, how to construct a Controller

Follow these steps to construct a Controller in CodeIgniter:

1. The name of your Controller should go in a new file in the “application/controllers” directory. For instance, if the name of your Controller is “Products,” the file’s name would be “Products.php.”

2. Declare the class using the file’s name. For example:

class Products extends CI_Controller {

}

3. Make methods for the class that reflect the user actions that may be taken on the application. For instance:

class Products extends CI_Controller {
    public function index() {
    // Code to display a list of products
    }

    public function show($id) {
    // Code to display a single product with the given ID
    }

    public function create() {
    // Code to display a form for creating a new product
    }

    public function store() {
    // Code to store the new product in the database
    }

    public function edit($id) {
    // Code to display a form for editing the product with the given ID
    }

    public function update($id) {
    // Code to update the product with the given ID in the database
    }
    
    public function delete($id) {
    // Code to delete the product with the given ID from the database
    }
}

Examples of common tasks a Controller can perform

Some common tasks that a Controller can perform in CodeIgniter include:

  • Retrieving data from the database
  • Validating user input
  • Redirecting the user to another page
  • Loading a View with data to be displayed to the user
  • Storing data in the session
  • Sending email notifications

VI. constructing a test application

Using the MVC framework of CodeIgniter, we will build a simple web application in this part. A list of items will be shown on the app’s single page.

1. Using the command line tool, start a new CodeIgniter project:

$ composer create-project codeigniter4/appstarter myapp

2. In the “app/Controllers” directory, add a new Controller with the name “Products.”

<?php namespace App\Controllers;
 use CodeIgniter\Controller;
class Products extends Controller
{
public function index()
{
$data = [
'products' => [
['name' => 'Product 1', 'price' => '10.00'],
['name' => 'Product 2', 'price' => '20.00'],
['name' => 'Product 3', 'price' => '30.00'],
]
];
return view('products/index', $data);
}
}

3. In the directory “app/Views/products,” add a new View with the name “index.php.”

<!DOCTYPE html>
<html>
<head>
    <title>Products</title>
</head>
<body>
    <h1>Products</h1>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($products as $product): ?>
                <tr>
                    <td><?= $product['name'] ?></td>
                    <td><?= $product['price'] ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>

4. To map the root URL to the “index” method of the “Products” Controller, update the routes in “app/Config/Routes.php.”

5. Using the command-line tool, launch the local development server:

$routes->get('/', 'Products::index');

6. Go to “http://localhost:8080” in your browser after it has been opened. You should see a table with the goods listed in it.

Explained the function of each component in the application

  • Controller: The “Products” Controller is in charge of processing the user’s request and returning a suitable answer. In this instance, it gets the products’ list from the database and sends it to the View for visual presentation.
  • View: The “index.php” View is in charge of showing the user the list of items. It takes the data that the Controller has supplied and produces it as an HTML table.
  • Routes: The routes in “app/Config/Routes.php” translate URLs to certain Controller methods. In this instance, the “index” method of the “Products” Controller is mapped to the root URL.

VII. Conclusion

We spoke about the advantages of adopting CodeIgniter’s MVC framework for web development in this blog article. Additionally, we discussed some typical duties a CodeIgniter Controller may carry out as well as how to design one. Finally, we illustrated the function of each component in the program by building a simple website using CodeIgniter’s MVC design.

Developers may organize their code more efficiently and make it simpler to maintain and grow by employing the MVC design. CodeIgniter is a fantastic option for developing web apps of any scale because of its vast documentation and broad feature set.

FAQs

Frequently asked questions

chevron down What are the benefits of using CodeIgniter's MVC architecture?

Using CodeIgniter's MVC architecture helps to keep code organized and maintainable, making it easier to test and modify individual components of the application without affecting the others

chevron down What kind of web applications can I build with CodeIgniter?

CodeIgniter can be used to build a wide variety of web applications, including e-commerce sites, content management systems, and social networking platforms.

chevron down Can I use CodeIgniter with other programming languages besides PHP?

CodeIgniter is specifically designed for use with PHP and is not compatible with other programming languages.