Apply for Zend Framework Certification Training

Codeigniter






         How to create custom Library in Codeigniter

Step - 1 Create library file Google_captha.php in library folder

< ?php
defined('BASEPATH') OR exit('NO direct Script Allowed');

class CI_Google_captha{
    function __construct(){
        $CI =& get_instance();
        $CI->load->helper('url');
        $CI->load->library('session');
        $CI->config->item('base_url');
    }
    function hello(){
        echo "Hello there";
    }
}

 

Step - 2    In autoload.php

$autoload['libraries'] = array('database','form_validation','google_captha');

Note :    Here   it is mendetory to  write libraray class name in small letters.

 

Step - 3   How to use this library in our controller

 public function index() {
    $this->google_captha->hello();
 }

Important :--

Here we have used get_instance  in our customized library contructor .

so 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('google_captha')

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("google_captha");

We use =& because we don't want to make a new copy of the CodeIgniter object,

we want to use the original one.

Example  :--

public function check_loggedin() {
     $CI =& get_instance();
     $CI->load->helper('url');
     $CI->load->library('session');
     $CI->config->item('base_url');
     if (!$CI->session->is_loggedin) {
         redirect('/index');
     }
 }

 

 

< First Getting Started With CodeIgniter URL Routing >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top