Creating Core Libraries
When we use the term "core libraries" we are normally referring to the base classes that are located in the libraries directory and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can create your own core libraries within your application directory in order to maintain separation between your local resources and the global framework resources.
Storage
In order for your libraries to be stored in your application folder you will need to create two directories in which to store them:
- application/init
- application/libraries
Anatomy of a Core Library
A core class library consists of two components:
- An init file.
- A class file.
The Init File
An init file a small initialization file corresponding to each of your classes. The purpose of this file is to instantiate a particular class. Each init file must be named identically to your class file name, adding the "init_" prefix. For example, if your class is named myclass.php your init file will be named:
init_myclass.php
Within your init file you will place your initialization code. Here's an example of such code, using an imaginary class named Myclass:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if ( ! class_exists('Myclass'))
{
require_once(APPPATH.'libraries/Myclass'.EXT);
}
$obj =& get_instance();
$obj->myclass = new Myclass();
$obj->ci_is_loaded[] = 'myclass';
?>
The Class File
Your class file itself will be placed inside your libraries directory:
application/libraries/myclass.php
The class will have this basic prototype:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Myclass {
}
?>
Naming Conventions
- All file names must be in lowercase: myclass.php and init_myclass.php
- Class names must be capitalize: class Myclass
Using Your Class
From within any of your Controller classes you can initialize your class using the standard:
$this->load->library('myclass');
Once loaded you can access your class using:
$this->myclass->function();
Note: In your init file you can define the object variable name.
Passing Parameters Your Class
In the library loading function you can pass data via the second parameter and it will be available to your initialization file:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('myclass', $params);
Parameters will be accessible using a variable called $params. By default this variable is set to FALSE.
Final Notes
Please note that $this will only be available if you are calling your class from within your Controllers or View files. If you need to access your class from elsewhere you'll need to use the get_instance() function to access the Code Igniter object. More information can be found in the Ancillary Classes page.