Welcome Guest, Not a member yet? Register   Sign In
Adding ajax supporting block support to CI modules
#1

[eluser]Peter Drinnan[/eluser]
I recently needed to add blocks to one of my CI apps.

If anyone has done this, please let me know how you approached it. Below is a summary wth code examples of how I did it.

Blocks for anyone unfamiliar with the term are usually used within a CMS and are like mini applications that can appear within the view of a parent application. Usually blocks appear on the top, left or right (in header or footer)of the application view, but can occasionally appear within the center of an application view. I could have coded these blocks as plugins or helpers, but in order to have them ajax enabled, they needed to be setup as both included objects and standalone (ajax responders) MVC instances.


Here's how I works:

///////////////////////////////
// First add this simple function to Base5.php

Code:
public static function set_instance($obj)
{
    self::$instance = & $obj;
}

/////////////////////////////////////////////////
// Second, added this variable to the Loader.php library

Code:
var $_ci_subcontrollers    = array();

//////////////////////////////////////////////////////
// Third add this simple (and crude I admit) function to the Loader.php library


Code:
/**
* The subcontroller is a mini application that can be called from within a parent
* application, but is a distinct instance. It can also be called via ajax
* so is designed to behave as a standalone MVC instance but can also be called as a subapplication
* from within a parent MVC instance
*/

function subcontroller($controllerfile){
    
    if (!in_array($controllerfile, $this->_ci_subcontrollers) && file_exists($controllerfile)){
        
        include($controllerfile);
        $this->_ci_subcontrollers[] = $controllerfile;
                
    }
}

///////////////////////////////////////////////////////////////////////////////////////////
// Finaly here is where the block gets called. Notice the use of get_instance and set_instance.


Code:
$controller_file =     APPPATH . "modules" . DS . "blocks" . DS . strtolower($block_type) . DS . "controllers" . DS . strtolower($block_type) . 'Controller.php';

// get the parent instance before loading the sub controller
$CI =& get_instance();
                                
$CI->load->subcontroller($controller_file);

$controller = "blocks_" . strtolower($block_type) . "Controller";
                                
if(!is_object($CI->$controller)){

    $CI->$controller = new $controller();
                                    
}
                
$outbuf .= $CI->$controller->index();

//restore the previous(parent) instance
set_instance($CI);




Theme © iAndrew 2016 - Forum software by © MyBB