Codelgniter 4 (CI4) Complete Beginner's Guid Step-by-Step, Fully Detailed

Codelgniter 4 (CI4) Complete Beginner's Guid Step-by-Step, Fully Detailed

CodeIgniter 4 (CI4) Complete Beginner’s Guide: Step-by-Step, Fully Detailed


Introduction

This blog is a comprehensive and extremely detailed guide for absolute beginners who want to learn CodeIgniter 4 (CI4). We'll break down every step and concept, making it as simple and clear as possible, while also covering essential details to ensure you fully understand how CI4 works.


What is CodeIgniter 4 (CI4)?

CodeIgniter 4 (CI4) is a modern PHP framework designed to simplify web application development. CI4 uses the MVC (Model-View-Controller) design pattern, which separates your application into:

  1. Model: Handles the database.
  2. View: Displays content to the user (HTML, CSS).
  3. Controller: Processes user requests and connects the Model and View.

Why Use CodeIgniter 4?

  1. Beginner-Friendly: Simple, readable, and easy to learn.
  2. Fast Development: Provides ready-to-use libraries for common tasks like database handling, session management, and routing.
  3. Performance: Lightweight, optimized for speed.
  4. Modern Features: Built for PHP 7.4+ with support for namespaces, composer integration, and modern security standards.

How to Set Up CodeIgniter 4

Step 1: Install CodeIgniter 4

There are two main ways to install CI4:

Option 1: Download the Framework

  1. Visit the CodeIgniter website.
  2. Download the latest version of CodeIgniter.
  3. Extract the zip file into your server’s root directory (e.g., htdocs if using XAMPP).

Option 2: Install via Composer (Recommended)

  1. Open your terminal or command prompt.

  2. Run the following command:

    composer create-project codeigniter4/appstarter my-ci4-app
    

    This creates a new folder my-ci4-app with the CodeIgniter framework.


Step 2: Run the Development Server

  1. Navigate to your project folder:

    cd my-ci4-app
    
  2. Start the built-in PHP development server:

    php spark serve
    
  3. Open your browser and visit:

    http://localhost:8080
    

    You’ll see the default CodeIgniter welcome page, confirming your setup is successful.


CodeIgniter 4 Project Structure

Let’s break down the main folders in CI4:

  1. app/ Folder: Your Application Code

    • Controllers: Handles requests (e.g., app/Controllers/).
    • Models: Manages database interactions (e.g., app/Models/).
    • Views: HTML templates and UI (e.g., app/Views/).
  2. public/ Folder: Publicly Accessible Files

    • Contains assets like CSS, JavaScript, and images.
    • The entry point for the application is index.php.
  3. system/ Folder: Framework Core

    • Contains the internal CodeIgniter files. Avoid modifying this folder.
  4. writable/ Folder: Temporary Data

    • Stores logs, cache, and session files.
  5. tests/ Folder: Testing

    • Contains files for unit and feature testing.

CodeIgniter 4 Basics

1. Create Your First Controller

Controllers process user requests and return responses.

Steps:

  1. Go to app/Controllers/.

  2. Create a file called Hello.php.

  3. Add this code:

    namespace App\Controllers;
    
    class Hello extends BaseController
    {
        public function index()
        {
            return "Hello, CodeIgniter 4!";
        }
    }
    
  4. Open your browser and visit:

    http://localhost:8080/hello
    

Explanation:

  • Namespace: App\Controllers defines the folder where this controller resides.
  • index() method: The default method executed when the controller is accessed.

2. Views: Display HTML

Views are responsible for rendering the user interface (UI).

Steps:

  1. Go to app/Views/.

  2. Create a file called welcome_message.php.

  3. Add the following HTML:

    Welcome to CodeIgniter 4

    
    

    This is your first view.

    
    
  4. Modify the index() method in your Hello controller:

    public function index()
    {
        return view('welcome_message');
    }
    

Now, visit http://localhost:8080/hello to see your custom view.


3. Routes: Map URLs to Controllers

Routes define how URLs are connected to specific controllers.

Steps:

  1. Open app/Config/Routes.php.

  2. Add a custom route:

    $routes->get('/greet', 'Hello::index');
    
  3. Now, visiting http://localhost:8080/greet will call the index() method in the Hello controller.


4. Models: Interact with the Database

Models handle database operations such as retrieving and saving data.

Steps:

  1. Create a database table named users:

    CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        email VARCHAR(100),
        created_at DATETIME,
        updated_at DATETIME
    );
    
  2. Go to app/Models/ and create a file called UserModel.php:

    namespace App\Models;
    
    use CodeIgniter\Model;
    
    class UserModel extends Model
    {
        protected $table = 'users';
        protected $primaryKey = 'id';
        protected $allowedFields = ['name', 'email'];
    }
    

Tips for Mastering CodeIgniter 4

  1. Read the Official Docs: Familiarize yourself with the CodeIgniter Documentation.
  2. Practice Often: Build small projects to solidify your understanding.
  3. Use Debugging Tools: Enable debug mode during development to catch errors easily.
  4. Learn Composer: Take advantage of composer to manage libraries and dependencies.
  5. Experiment with Features: Explore CI4 features like REST APIs, data validation, and database migrations.

PS 

CodeIgniter 4: Beginner's Guide

CodeIgniter 4 is a modern PHP framework known for its lightweight, speed, and ease of use. This guide will help you get started with CodeIgniter 4 and introduce you to its core components.

1. Installing CodeIgniter 4

There are several ways to install CodeIgniter 4. We will cover installation using Composer, which is the recommended method.

Using Composer

If you have Composer installed on your computer, you can simply run the following command:

composer create-project codeigniter4/appstarter my_project

This will create a my_project directory and download the necessary CodeIgniter 4 files.

Downloading ZIP File

You can also download the ZIP file for CodeIgniter 4 from the official website https://codeigniter.com/download, extract it, and place it on your server.

2. File Structure

After installation, the project has the following structure:

my_project/
├── app/           # Main application folder
├── public/        # Public files (index.php)
├── system/        # Core CodeIgniter libraries
├── writable/      # Temporary files, cache, logs
├── tests/         # For unit testing
└── .env           # Environment variables

Important folders:

  • app/ – Contains the main application files (Controllers, Models, Views).
  • public/ – Should contain index.php, CSS, and JavaScript files.
  • writable/ – Stores cache, logs, and temporary data.

3. Creating the First Controller

Controllers in CodeIgniter handle HTTP requests. To create a new controller, create a file named Home.php inside the app/Controllers folder with the following code:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Home extends Controller
{
    public function index()
    {
        return "Hello, CodeIgniter 4!";
    }
}

This controller returns a simple text message – "Hello, CodeIgniter 4!".

4. Managing Routing

CodeIgniter 4 has a flexible routing system. The main routing file is located at app/Config/Routes.php.

For example, you can add a new route:

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

This means that when a user visits example.com/welcome, the index() method of the Home class will be executed.

5. Creating a View File

View files are responsible for rendering HTML output. Create a new file app/Views/welcome_message.php with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to CodeIgniter 4</title>
</head>
<body>
    <h1>Welcome to CodeIgniter 4!</h1>
</body>
</html>

Next, update the Home controller to load this view:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Home extends Controller
{
    public function index()
    {
        return view('welcome_message');
    }
}

Now, when you visit example.com/, you will see your first CodeIgniter 4 webpage!

6. Connecting to a Database

CodeIgniter 4 provides a simple and flexible database management system. You can configure the database connection in the .env file:

database.default.hostname = localhost
database.default.database = my_database
database.default.username = root
database.default.password = my_password
database.default.DBDriver = MySQLi

Next, using the Model class, we can retrieve and manage data. For example, creating a new model:

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'password'];
}

Fetching data inside a Controller:

<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\Controller;

class UserController extends Controller
{
    public function index()
    {
        $userModel = new UserModel();
        $users = $userModel->findAll();
        return view('users_list', ['users' => $users]);
    }
}

Conclusion

In this guide, we covered: ✅ Installing CodeIgniter 4 ✅ File structure ✅ Creating the first controller ✅ Managing routing ✅ Using view files ✅ Connecting to a database and using the Model class

CodeIgniter 4 is a powerful and flexible framework that makes modern PHP development easy. The next step could be implementing CRUD operations in the database! 🚀



Conclusion

CodeIgniter 4 is powerful yet beginner-friendly. Start small, follow this guide, and soon you’ll be building your own professional web applications. Good luck!