CodeIgniter 4 HMVC applications are built using the HMVC Architecture Pattern, which allows for greater modularity and flexibility. This architecture, based on the traditional MVC pattern, enables the development of independent modules, each containing its own Model, View, and Controller components. This modular structure simplifies maintenance and encourages code reuse across different parts of the application.
Table Of Content
1 Prerequisites
1.) PHP version of 8.2
2.) MySql
2 Introduction
In this article, we explore the CodeIgniter 4 HMVC application in detail. We’ll walk through how to set up HMVC integration in CodeIgniter 4, and look at examples of applications built using the CodeIgniter 4 HMVC Architecture Pattern.
3 Create / Install a Codeigniter 4 Project
3.1 Install Codeigniter 4 Project
To get started, ensure that you have Composer installed on your computer. Use the following command to install a new CodeIgniter project:
To set up HMVC integration in CodeIgniter 4, create a new directory called Modules under the app folder. For instance, you can create a module named Blog, containing controllers, models, and views subdirectories.
5 Register your custom namespace
Next, register the namespace for the Modules/Blog in app/Config/Autoload.php by adding the following to the psr4 array:
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
class Autoload extends AutoloadConfig
{
// ...
public $psr4 = [
APP_NAMESPACE => APPPATH,
'Modules\Blog' => ROOTPATH . 'Modules/Blog',
];
// ...
}
6 Create Migration and Model
Create a migration for the posts table to store your data. Also, create a model PostModel. Run this command to generate the model:
In app/Modules/Controllers/BlogController.php, load the PostModel and fetch all posts to display in the view.
<?php
namespace Modules\Blog\Controllers;
use App\Controllers\BaseController;
use App\Modules\Blog\Models\PostModel;
class BlogController extends BaseController
{
private $postModel;
public function __construct()
{
$this->postModel = new PostModel();
}
public function index()
{
$data = [
'posts' => $this->postModel->findAll(),
];
return view('post',$data);
}
}
?>
8 Create Post View File
Create the post.php file inside app/Modules/Blog/Views. This file will display the posts fetched from the database.