Create Simple Codeigniter library Create Simple Codeigniter library codeigniter codeigniter

Create Simple Codeigniter library


One thing I notice: remove the parent::__construct() from your library constructor, because it's not extending anything so has no parent to call.

Also, enable error reporting by setting the environment to "development" in index.php, and you might also want to raise the logging threshold to 4 in config/config.php so you log errors.

Try this simple test-case:

file Pro.php in application/libraries:

class Pro {  function show_hello_world()  {    return 'Hello World';  }}

Controller admin.php in application/controllers

class Admin extends CI_Controller{    function index()    {        $this->load->library('pro');        echo $this->pro->show_hello_world();    }}


while your class name is capitalized, all your references to the library when loading it and using it should be lower case. you also do not need the constructor, as the other commenter mentioned.

so instead of:

echo($this->Pro->show_hello_world());

you should have:

echo($this->pro->show_hello_world());


I prefer the standard php autoloader approach, with this you dont need to change your classes at all, you can use your standard classes without modifications

say for instance you class is class 'Custom_Example_Example2' and is stored in libraries in sub folders you can add this autoloader in the master index.php

make sure it is added below the defined APPPATH constant

//autoload custom classesfunction __autoload($className) {if (strlen(strstr($className, 'Custom_')) > 0 ||   strlen(strstr($className, 'Other1_')) > 0 ||   strlen(strstr($className, 'Other2_')) > 0) {    $exp  = explode('_', $className);    $file = APPPATH.'libraries';    if(!empty($exp)) {        foreach($exp as $segment) {            $file .= '/'.strtolower($segment);        }    }    $file .= '.php';    require_once $file;    //debug    //echo $file.'<br />';}}

This will look for class calls matching the 'Custom_' prefixand reroute them to the relative location in this case

you only need to define the base prefix not the sub folders / classesthese will be auto detected by this code

APPPATH.'libraries/custom/example/example2.php'

You can call it in the controller the standard php way

$class = new Custom_Example_Example2;

or

$class = new custom_example_example2();

You can modify the script to your liking currently it expects all folders and filenames in the library to be lowercase but you can remove the strtolower() function to allow multiple casing.

you can change the require once to echo to test the output by uncommenting this line and refresh the page, make sure you have a class init / test in the controller or model to run the test

echo $file.'<br />';

ThanksDaniel