Java Like Import

Derek Jones edited this page Jul 5, 2012 · 5 revisions
Clone this wiki locally

This is a primitive java like import for CI.

**CAUTION **: It may produce unpredictable result If you have two class with the same name (even if you put it in a different file/package).

You must enable hooks first at yout config.php


$config['enable_hooks'] = TRUE;

Add a hooks configuration at hooks.php


$hook['pre_system'] = array(
                          'class'    => '',
                          'function' => 'fake',
                          'filename' => 'ClassLoader.php',
                          'filepath' => 'hooks'
                      );

Create ClassLoader.php under hooks directory


<?php
function fake(){
    // do nothing
}

function import($class, $package = 'package')
{    
    $class = $package . "/" . $class;
    $class = str_replace(".", "/", $class);
    $path  = APPPATH . $class . EXT;    
    
    if(file_exists($path)){
        require_once($path);
        return true;
    }else{
        return false;
    }

}
?>

Create a folder named 'package' under application directory. This directory is the home for your own class.

Example: We create a class BaseController on package/com/company/project/controller/BaseController.php


<?php
// extends CI Controller
class BaseController extends Controller {
    
    function BaseController(){
        parent::Controller();
    }
    
}

?>

At your regular controller you can import base controller like this:


<?php

import('com.company.project.controller.BaseController');
// you can import other class here

class Homepage extends BaseController{
    
    function Homepage(){
        parent::BaseController();    
    }
    
    function index(){
             echo "test";
    }
}
?>