Setup HMVC with Codeigniter 2.1.4

This is an example on HMVC Codeigniter 2. HMVC stands for Hierarchical Model View Controller. Modular Extensions make the Codeigniter PHP framework modular. Modules are groups of independent components, typically model, controller and view, arranged in an application modules sub-directory that can be dropped into other Codeigniter applications. This allows easy distribution of independent components (MVC) in a single directory across other CodeIgniter applications.

Module Controllers can be used as normal Controllers or HMVC Controllers and they can be used as widgets to help you build view partials.
You can download the HMVC package from https://github.com/Crypt/Codeigniter-HMVC

Basic structure for HMVC

[xml]
/modules
/module1
/controllers
/config
/helpers
/language
/libraries
/models
/module2
/controllers
/config
/helpers
/language
/libraries
/models
[/xml]

Features

Modules can be stored in several locations by modifying MY_Router.php
Each module may contain a config/routes.php file where routing and a default controller can be defined for that module. The default controller should be set using $route[‘module_name’] and NOT $route[‘default_controller’].
$route[‘404_override’] can be set in application/routes.php to send all 404 requests to a certain module.
Controllers may be loaded from application/controllers.
Controllers may also be loaded from module/controllers.
All module controllers are accessible from the URL via module/controller/method or simply module/method if the module and controller names match.
You can still use _remap() in your controllers

Key advantages of HMVC pattern

Modularization: Reduction of dependencies between the disparate parts of the application.
Organization: Having a folder for each of the relevant triads makes for a lighter work load.
Reusability: By nature of the design it is easy to reuse nearly every piece of code.
Extendibility: Makes the application more extensible without sacrificing ease of maintenance.

Setup

1. Download the modular package from the above link provided

2. Unzip the hmvc modular extensions package.

3. Copy all the files from the newly extracted folder’s ./core/ directory to Codeigniter’s /application/core/ directory on your server. (See content below)

4. Move the MX directory and all of its files from the newly extracted folder’s ./third-party/ directory
to CodeIgniter’s /application/third-party/ directory on your server.

5. Create a new folder called modules under application, where you will create your HMVC modules for a project.

6. The Modules::$locations array may be set in the application/config/config.php file, i.e.

/*
  |--------------------------------------------------------------------------
  | HMVC Modular
  |--------------------------------------------------------------------------
  |
  | Modules location
 */
$config['modules_locations'] = array(
    APPPATH . 'modules/' => '../modules/',
);

 

Modules::run() output is buffered, so any data returned or output directly from the controller is caught and returned to the caller. In particular, $this->load->view() can be used as you would in a normal controller, without the need for return.

Controllers can be loaded as class variables of other controllers using $this->load->module(‘module/controller’); or simply $this->load->module(‘module’); if the controller name matches the module name. Controllers may be loaded from application/controllers sub-directories. Controllers may also be loaded from module/controllers sub-directories. Resources may be cross loaded between modules, i.e., $this->load->model(‘module/model’);

For example

class Hello extends CI_Controller {
    public function index() {
        // load a model from the current module
        $this->load->model('local_model');
        // load a model from another module
        $this->load->model('other_module/model');
        // HMVC example
        $this->load->controller('module/controller/method', $params = array(), $return = FALSE);
    }
}

 

Any loaded module controller can then be used like a library, ie: $this->controller->method(), but it has access to its own models and libraries independently from the caller.

All module controllers are accessible from the URL via module/controller/method or simply module/method if the module and controller names match. If you add the _remap() method to your controllers you can prevent unwanted access to them from the URL and redirect or flag an error as you like.

Notes

You must use PHP5 style constructors in your controllers. Constructors are not required unless you need to load or process something when the controller is first created.

To use HMVC functionality, such as Modules::run(), controllers must extend the MX_Controller class.

For example

class Hello extends MX_Controller
{
    function __construct()
    {
        parent::__construct();
    }
}

 

To use Modular Separation only, without HMVC, controllers will extend the Codeigniter Controller class.

For example

class Hello extends CI_Controller {
    function __construct()
    {
        parent::__construct();
    }
}

 

Each module may contain a config/routes.php file where routing and a default controller can be defined for that module using:

$route['module_name'] = 'controller_name';

 

When using form validation with MX you will need to extend the CI_Form_validation class as shown below:

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class MY_Form_Validation extends CI_Form_validation {
    function run($module = '', $group = '') {
        (is_object($module)) AND $this->CI = &$module;
        return parent::run($group);
    }
}
/* End of file my_form_validation.php */
/* Location: ./application/libraries/my_form_validation.php */

 

The above file my_form_validation.php should be put into /application/libraries directory.

The below example shows how form validation is run on HMVC

Suppose we have a login page with username and password inputs. When user enter username and password then validation happens and takes user to the user’s home page. If validation fails then it takes user back to the login page.

class Login extends MX_Controller
{
    function __construct()
    {
        parent::__construct();
    }
    
    public function index() {
        $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[20]|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|max_length[20]|xss_clean');
        if ($this->form_validation->run($this)) { //validation pass
            redirect('home');
        }
        $this->load->view('login');
    }
}

 

If you want to remove the index.php from URL then you can go through remove index.php from URL.

That’s all. Thank you for reading. Please feel free to post a comment.

1 thought on “Setup HMVC with Codeigniter 2.1.4

Leave a Reply

Your email address will not be published. Required fields are marked *