CodeIgniter 4 HMVC Programming Tutorial

Share this Article
Reading Time: 7 minutes
49 Views

Inside this article we will see the concept of CodeIgniter 4 HMVC Programming. This is very interesting tutorial to see and learn module development in CodeIgniter.

Here, we have a complete course over HMVC Programming in CodeIgniter 4. You can enrol to learn in depth with easiest steps.

HMVC stands for Hierarchical Model View Controller. We will see few concepts in detail here.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


What is HMVC Programming in CodeIgniter 4?

CodeIgniter is php based framework and works on MVC (Model-View-Controller) pattern. It can
also use the Hierarchical Model View Controller (HMVC).

In CodeIgniter HMVC, HMVC stands for Hierarchical Model View Controller. It is a further new
version of the MVC pattern used for web applications. Providing solutions to many problems it
helps you solve the scalability of applications.

For Example –

School -> Teachers, Students, Books, Academics, Transport, finance etc.

Let’s say we have an application called School web application. If we follow MVC then, in a single setup we need to develop each section of application.

But when we create via HMVC programming, then each section will be a module. Each module is a separate application setup.

Have a look this image, one side is MVC of application and other side we have HMVC which means module wise collection and each module has a MVC structure.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


HMVC Module Setup

Go to your project setup, at root create a folder called Modules. We will create module inside this folder and the combine with application.

Next, let’s create folder called Student into /Modules folder.

So, we have /Modules/Student folder at project root alongwith other application folders like /app, /public, etc.

Module Registration / Module Autoload

Open Autoload.php from /app/Config folder. Now, we need to register Student Module into it. If we register module then we will be able to find the path at terminal as well.

Search for $psr4 and register created module in it.

public $psr4 = [
     APP_NAMESPACE => APPPATH, // For custom app namespace
     'Config' => APPPATH . 'Config',
    'Modules\Student' => ROOTPATH. 'Modules/Student', // here we have added.
];

Module – Create Controller

Open project into terminal and type this spark command to create controller into Student Module.

$ php spark make:controller Student --suffix --namespace "Modules\Student"

It will create a file named StudentController.php into /Modules/Student/Controllers folder. In command “Modules\Student” is the namespace we have given to create controller inside this.

Open file StudentController.php and write this code into it.

<?php

namespace Modules\Student\Controllers;

use App\Controllers\BaseController;
use Modules\Student\Models\StudentModel;

class StudentController extends BaseController
{
	public function index()
	{
		// echo "This is simple from Student Module";

        $data = [ "name" => "Sanjay", "email" => "sanjay_kumar@gmail.com" ]

		return view("\Modules\Student\Views\student_index", $data);
	}
  
    public function otherMethod()
	{
		echo "This is other method from Student Module";
	}
}

Into this controller file, we have a simple method called index() into it.


Module – View File Setup

Create a folder with the name Views inside /Modules/Student.

Create a view file i.e student_index.php into it.

<h1>Hi, this is view file from Student Module</h1>
  
<p>Name: <?= $name ?>  </p>
<p>Email: <?= $email ?> </p>

Module – Create Route

Create a folder with name Config into /Modules/Student.

Create a file i.e Routes.php into it. Inside this file, we will do all routes settings for student module.

<?php

$routes->group("student", ["namespace" => "\Modules\Student\Controllers"], function ($routes) {

	// welcome page - URL: /student
	$routes->get("/", "StudentController::index");
  
    // other page - URL: /student/other-method
	$routes->get("other-method", "StudentController::otherMethod");

});

Here, we have create a route group in which /student will be the prefix for each route.

Including Module routes into Main application

Open Routes.php file from /app/Config. This is main routes file of application.

//.. Other routes

// Add this to Footer

// Including all module routes

$modules_path = ROOTPATH . 'Modules/';
$modules = scandir($modules_path);

foreach ($modules as $module) {
	if ($module === '.' || $module === '..') {
		continue;
	}

	if (is_dir($modules_path) . '/' . $module) {
		$routes_path = $modules_path . $module . '/Config/Routes.php';
		if (file_exists($routes_path)) {
			require $routes_path;
		} else {
			continue;
		}
	}
}

This code is looking for /Modules folder, if there then including Routes.php from each module’s Config folder.


Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/student

Method will be called – /Modules/Student/Controllers/StudentController::index()

URL: http://localhost:8080/student/other-method

Method will be called – /Modules/Student/Controllers/StudentController::otherMethod()

We hope this article helped you to CodeIgniter 4 HMVC Programming Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment