How to create Custom Library in codeigniter?
Codeigniter libraries means classes which located in libraries directory. so for create our own custom library in codeigniter we need to build classes and store class file in libraries directory full path of libraries directory will be “application/libraries”. It’s easy to create new/ custom library , replace native or extend native library in codeigniter.
Below in this tutorial we will discuss :-
Create new/custom libraries
Using new/custom libraries
Extend native libraries
Create new/custom libraries :- We need to create our own or custom library to add some new functionality.
Library rules / naming :-
New library file must be stored in "application/libraries" directory.
Library file names must be capitalized. like: Example.php
Class declarations in library must be capitalized. like: class Example
Library class name and library file name must match.
Class Example :- creating a "Example.php" file under "application/libraries/Example.php" and add below code.
File name : Example.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Example {
public function my_function() {
// do your stuff
}
}
Using new/custom libraries :- After create custom library let’s see how to use this library in controller/model/view.
Include or initialize library :- first you need to include library to use functionality to include call below function where you need. Need to pass filename(case insensitive) “example” without “.php” extension.
$this->load->library('example');
// or $this->load->library('Example');
or autoloading library by "applications/config/autoload.php" (will include for all pages)
$autoload['helper'] = array('example');
Passing parameters on class Initialization :- for this your class must have a constructor
File name : index.php
$arr = array('name'=>'mahtab');
$this->load->library('example', $arr);
//class
class Example {
public function __construct($arr) {
// Do your stuff with $arr
}
}
Calling library function :- after load you can access class function with Object instances will be lower case.
$this->example->my_function();
Passing parameter to function:-
<p>$arr = array('name'=>'mahtab');<br />
$this->example->my_function($arr);<br />
// class function :- public function my_function($arr){}</p>
Use codeigniter resources in Library :- you can also use another library, config, helper etc. in your custom library with CI instance like
$CI =& get_instance();
$CI->load->helper('myhelper');
$CI->load->library('email');
$CI->config->item('myitem');
Extend native libraries :- extend means you are adding some more functionality to existing library. for extend native library your
library name must be start with MY_
Class must extend parent class.
First Add class prefix to config :- go to applications/config/config.php and add subclass_prefix
$config['subclass_prefix'] = 'MY_';
We are going to extend CI_Form_validation :- create a file MY_Form_validation.php under “application/libraries/MY_Form_validation.php” and adding new form validation
Now need to include this library :-
$this->load->library('form_validation');
and call this validation rule like:-
$this->form_validation->set_rules('name',Name', 'trim|required|xss_clean|alpha_space');
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
// check for alpha and space
function alpha_space($str) {
return ( ! preg_match("/^([a-z ])+$/i", $str)) ? FALSE : TRUE;
}
}
http://www.anil2u.info/2015/03/how-to-create-custom-library-file-in-codeigniter/
How to create custom library file in CodeIgniter
Step 1 :
Go to folder application -> libraries
Step 2 :
Create a PHP file with YourLibraryName_lib.php
Step 3 :
Starting of library file write below code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author Anil Kumar Panigrahi
* @copyright Copyright (c) 2015, Anil Labs.
* @license
* @link http://www.anil2u.info
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Anil Labs core CodeIgniter class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Anil Labs
* @author Anil Kumar Panigrahi
* @link http://www.anil2u.info
*/
Note: We can change description according to your requirement.
Step 4 :
Create library class with database connection and load the pre-defined libraries
class Anillabs_lib {
var $CI;
public function __construct($params = array())
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->config->item('base_url');
$this->CI->load->database();
}
Step 5
We can write your function to manipulate
public function getMetadata($pageid){
$sql = "SELECT * FROM pages WHERE pageid = ?";
$results = $this->CI->db->query($sql, array($pageid));
$pageMetadata = $results->row();
$data['keywords'] = $pageMetadata->keywords;
$data['description'] = $pageMetadata->description;
$this->CI->load->view('templates/header',$data);
}
Step 6 :
Go to /application/config/autoload.php
Search for
$autoload['libraries']
and add your library file which you need to allow in complete application. If you don’t want to allow in complete application then we can write below code in single controller
$this->load->library('anillabs_lib');
Step 7 :
Once you load library file in above step, next calling library file in your controller method like below
$this->anillabs_lib->getMetadata(5);
Complete library file code :-
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author Anil Kumar Panigrahi
* @copyright Copyright (c) 2015, Anil Labs.
* @license
* @link http://www.anil2u.info
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Anil Labs core CodeIgniter class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Anil Labs
* @author Anil Kumar Panigrahi
* @link http://www.anil2u.info
*/
class Anillabs_lib {
var $CI;
public function __construct($params = array())
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->config->item('base_url');
$this->CI->load->database();
}
public function getMetadata($pageid){
$sql = "SELECT * FROM pages WHERE pageid = ?";
$results = $this->CI->db->query($sql, array($pageid));
$pageMetadata = $results->row();
$data['keywords'] = $pageMetadata->keywords;
$data['description'] = $pageMetadata->description;
$this->CI->load->view('templates/header',$data);
}
}
How to create custom library.
File Name : Mylibrary.php
creare Mylibrary class in library directory.
<?php
class Mylibrary
{
public function myinfo()
{
echo "say hello my library";
}
}
Controller
File Name : Customlibrary.php
<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class Customlibrary extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('mylibrary');
}
public function index()
{
echo $this->mylibrary->myinfo();
}
}
http://tutsnare.com/create-custom-library-in-codeigniter/
Example
Create Auth Library
File Name : Auth.php
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Auth
{
var $CI;
var $session_expire = 600;
public function __construct()
{
// parent::__construct();
// remove the parent::__construct() from your library constructor, because it's not extending anything so has no parent to call.
// $CI =& get_instance(); // if $CI is not declare instance variable
$this->CI =& get_instance();
$this->CI->load->database();
$this->CI->load->library('encryption');
$this->CI->load->helper('url');
}
function login_admin($userid, $password, $remember=false)
{
/* $this->CI->db->select('*');
$this->CI->db->where('user_id', $userid);
$this->CI->db->where('password', ($password));
$this->CI->db->limit(1);
$query = $this->CI->db->get('admin_info');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}*/
$this->CI->db->select('*');
$this->CI->db->where('userid', $userid);
$this->CI->db->where('password', ($password));
$this->CI->db->limit(1);
$result = $this->CI->db->get('admin');
$result = $result->row_array();
if (sizeof($result) > 0)
{
$admin['id'] = $result['id'];
$admin['userid'] = $result['userid'];
$admin['email'] = $result['email'];
$this->CI->session->set_userdata('logdinUser',$admin);
/* $admin = array(
'id' => $result['id'],
'userid' => $result['userid'],
'email' => $result['email'],
'loginuser' => TRUE
);
$this->CI->session->set_userdata($admin);
*/
if(!$remember)
{
$admin['admin']['expire'] = time()+$this->session_expire;
}
else
{
$admin['admin']['expire'] = false;
}
return true;
}
else
{
return false;
}
}
/* ***************** Logout ************************** */
public function logout()
{
$this->CI->session->unset_userdata('logdinUser');
$this->CI->session->sess_destroy();
}
/* **************End Logout ****************** */
/* **************** check login exist or not ********************** */
function is_logged_in($redirect = false, $default_redirect = true)
{
$admin = $this->CI->session->userdata('logdinUser');
if (!$admin) // if user not logged in.
{
if ($redirect)
{
$this->CI->session->set_flashdata('redirect', $redirect);
}
if ($default_redirect)
{
redirect($this->CI->config->item('admin_folder').'/login');
//redirect('admin/login');
}
return false;
}
else
{
// if user is logged in.
//check if the session is expired if not reset the timer
if($admin['expire'] && $admin['expire'] < time())
{
$this->logout();
if($redirect)
{
$this->CI->session->set_flashdata('redirect', $redirect);
}
if($default_redirect)
{
redirect('admin/login');
}
return false;
}
else
{
//update the session expiration to last more time if they are not remembered
if($admin['expire'])
{
$admin['expire'] = time()+$this->session_expire;
$this->CI->session->set_userdata(array('admin'=>$admin));
}
}
return true;
}
}
/* **************** end check login exist or not ********************** */
/* ********************** Reset Password ******************************* */
function reset_password($email)
{
$admin = $this->get_admin_by_email($email);
if ($admin)
{
$this->CI->load->helper('string');
$this->CI->load->library('email');
$new_password = random_string('alnum', 8);
//$admin['password'] = sha1($new_password);
$admin['password'] = $new_password;
$this->save_admin($admin);
/*
$this->CI->email->from($this->CI->config->item('email'), $this->CI->config->item('site_name'));
$this->CI->email->to($email);
$this->CI->email->subject($this->CI->config->item('site_name').': Admin Password Reset');
$this->CI->email->message('Your password has been reset to '. $new_password .'.');
//$this->CI->email->send();
*/
/*
$this->load->library('email');
$this->email->clear(TRUE);
$this->email->from($this->CI->config->item('email'), 'Your Name');
$this->email->to($email);
//$this->email->cc('another@another-example.com');
//$this->email->bcc('them@their-example.com');
$this->email->subject($this->CI->config->item('site_name').': Admin Password Reset');
$this->email->message('Your password has been reset to '. $new_password .'.');
$this->email->send();
if ($this->email->send(FALSE))
{
// This method will automatically clear all parameters if the request was successful. To stop this behaviour pass FALSE
}
*/
$this->CI->session->set_flashdata('passmsg','<div class="alert alert-success text-center">Your Password has been sent successfully! Please check your mail.</div>');
return true;
}
else
{
return false;
}
}
/* ************************** End Reset Password ********************************* */
private function get_admin_by_email($email)
{
$this->CI->db->select('*');
$this->CI->db->where('email', $email);
$this->CI->db->limit(1);
$result = $this->CI->db->get('admin');
$result = $result->row_array();
if (sizeof($result) > 0)
{
return $result;
}
else
{
return false;
}
}
/*
This function takes admin array and inserts/updates it to the database
*/
public function save_admin($admin)
{
if ($admin['id'])
{
$this->CI->db->where('id', $admin['id']);
$this->CI->db->update('admin', $admin);
}
else
{
$this->CI->db->insert('admin', $admin);
}
}
/* ******************************************* */
public function change_password($email,$newpass)
{
$admin = $this->get_admin_by_email($email);
if ($admin)
{
$this->CI->load->helper('string');
$this->CI->load->library('email');
//$new_password = random_string('alnum', 8);
//$admin['password'] = sha1($new_password);
$admin['password'] = $newpass;
$this->change_admin_password($admin,$newpass);
$this->CI->session->set_flashdata('passmsg','<div class="alert alert-success text-center">Your Password has been change successfully!</div>');
return true;
}
else
{
return false;
}
}
public function change_admin_password($admin,$newpass)
{
if ($admin['id'])
{
$this->CI->db->where('id', $admin['id']);
$this->CI->db->set('password',$newpass);
$this->CI->db->update('admin', $admin);
}
else
{
$this->CI->db->insert('admin', $admin);
}
}
/*
This function gets a complete list of all admin
*/
function get_admin_list()
{
$this->CI->db->select('*');
$this->CI->db->order_by('userid', 'ASC');
$this->CI->db->order_by('password', 'ASC');
$this->CI->db->order_by('email', 'ASC');
$result = $this->CI->db->get('admin');
$result = $result->result();
return $result;
}
/*
This function gets an individual admin
*/
function get_admin($id)
{
$this->CI->db->select('*');
$this->CI->db->where('id', $id);
$result = $this->CI->db->get('admin');
$result = $result->row();
return $result;
}
function check_id($str)
{
$this->CI->db->select('id');
$this->CI->db->from('admin');
$this->CI->db->where('id', $str);
$count = $this->CI->db->count_all_results();
if ($count > 0)
{
return true;
}
else
{
return false;
}
}
function check_email($str, $id=false)
{
$this->CI->db->select('email');
$this->CI->db->from('admin');
$this->CI->db->where('email', $str);
if ($id)
{
$this->CI->db->where('id !=', $id);
}
$count = $this->CI->db->count_all_results();
if ($count > 0)
{
return true;
}
else
{
return false;
}
}
function delete($id)
{
if ($this->check_id($id))
{
$admin = $this->get_admin($id);
$this->CI->db->where('id', $id);
$this->CI->db->limit(1);
$this->CI->db->delete('admin');
return $admin->firstname.' '.$admin->lastname.' has been removed.';
}
else
{
return 'The admin could not be found.';
}
}
/*
public function add_admin_user($data)
{
$this->CI->db->insert('admin',$data);
}
*/
public function add_admin_user()
{
$userid = $this->CI->input->post('userid');
$password = $this->CI->input->post('password');
$email = $this->CI->input->post('email');
$mobile = $this->CI->input->post('mobile');
$data = array(
'userid' => $userid,
'password' => $password,
'email' => $email,
'mobileno' => $mobile
);
$this->CI->db->insert('admin',$data);
}
}
Create Login Controller
File Name : Login.php
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
//force_ssl();
$this->load->library('Auth');
$this->load->helper('language');
$this->lang->load('login');
$this->load->helper('form');
}
public function index()
{
$redirect = $this->auth->is_logged_in(false, false);
echo $redirect;
//if they are logged in, we send them back to the dashboard by default, if they are not logging in
if ($redirect)
{
redirect($this->config->item('admin_folder').'/dashboard');
//redirect('admin/dashboard');
}
$this->load->view($this->config->item('admin_folder').'/login');
}
public function logincheck()
{
$userid = $this->input->post('uid');
$password = $this->input->post('pass');
$remember = $this->input->post('remember');
$login = $this->auth->login_admin($userid, $password, $remember);
if ($login > 0)
{
//redirect('admin/dashboard');
redirect($this->config->item('admin_folder').'/dashboard');
}
else
{
$this->session->set_flashdata('error', lang('error_authentication_failed'));
//redirect('admin/login');
redirect($this->config->item('admin_folder').'/login');
}
}
}
Dashboard Controller
File Name : Dashboard.php
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard extends CI_Controller {
function __construct()
{
parent::__construct();
$loggedIn = $this->session->userdata('logdinUser');
//print_r($loggedIn['id']);
if($loggedIn == TRUE)
{
}
else
{
redirect('admin/login');
}
}
public function index()
{
$this->load->view('admin/header');
$this->load->view('admin/dashboard');
$this->load->view('admin/footer');
}
public function Calendar()
{
$data['getEmployee'] = $this->EmployeeModel->getEmployee();
$data['getHoliday'] = $this->EmployeeModel->getHoliday();
$data['getAttendance'] = $this->EmployeeModel->getAttendance();
$data['getSalary'] = $this->EmployeeModel->getSalary();
$data['getShift'] = $this->EmployeeModel->getShift();
$data['getShiftAttendance'] = $this->EmployeeModel->getShiftAttendance();
$this->load->view('admin/header');
$this->load->view('admin/dashboard',$data);
$this->load->view('admin/footer');
}
}
Logout Controller
File Name : Logout.php
<?php
defined('BASEPATH') OR exit('no script direct access allowed');
class Logout extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('Auth');
$this->lang->load('login');
$this->load->helper('language');
$loggedIn = $this->session->userdata('logdinUser');
if($loggedIn == TRUE)
{
}
else
{
redirect('admin/login');
}
}
public function index()
{
//$this->session->set_flashdata('message', 'Successfully Logout');
$this->session->set_flashdata('message', lang('message_logged_out'));
//redirect($this->config->item('admin_folder').'/login');
$this->auth->logout();
//redirect('admin/login');
$this->load->view('admin/login');
//redirect('admin/login','refresh');
/* $this->session->unset_userdata('userid');
$this->session->sess_destroy();
$data['message'] = 'Successfully Logout';
$this->load->view('admin/login', $data);
*/
}
}
when to use get_instance()
If you are writing code that lives within a controller, a model or a view that is under CodeIgniter's control then you do not need to use get_instance.
If however you are writing your own custom libraries or something that sits outside of the MVC files then you do need to use it.
So, if you are inside a model you could do something like this;
$this->load->library('my_cool_library')
But if you are in a class you have written yourself then the $this object will not know about the CodeIgniter stuff, so you would do something like this;
$ci=& get_instance();
$ci->load->library("my_cool_library")
We use =& because we don't want to make a new copy of the CodeIgniter object, we want to use the original one.
File Name :
get_instance()
Any class that you instantiate within your controller methods can access CodeIgniter's native resources simply by using the get_instance() function. ...
Normally, to call any of the available methods, CodeIgniter requires you to use the $this construct:
You can utilize all of Code Igniter’s native resources using $this instance. But $this instance only works within your controllers, your models, or your views.
If you would like to use Code Igniter’s native resources from within your own custom classes you can do so as follows:
$obj =& get_instance();
Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:
$obj =& get_instance();
$obj->load->helper('url');
$obj->load->library('session');
$obj->config->item('base_url');
if you want to declare a helper for common script of access some table data, then you need to declare instance for access database class. example
helper/common_helper.php
function Statelist(){
$ci = & get_instance();
$sql = $ci->db->query("select * from states");
return $sql->result();
}
Previous
Next