Tuesday 3 March 2015

How to create custom library in CodeIgniter


How to create custom library in CodeIgniter


We are normally referring to the classes that are located in the libraries directory.
You can create your own libraries within your application/libraries directory.

Here
1)You can replace native and extend libraries.
2) You can create new libraries.




If You want to create library. then it place in application/libraries in codeigniter.

When you create new library there 3 thing for naming conversion.

  1. File names must be capitalized. For example:  Myexample.php
  2. Class declarations must be capitalized. For example:  class Myexample
  3. Class names and file names must match

Example OF custom library

create directory application/libraries/Pro.php file

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>

<?php



class Pro{

public function show_me(){
   
    return "Don Return";
 }
}

?>

this library use in your controller

here i am create my controller application\controllers\Test.php here initialize library.

class Test extends CI_Controller
{
    function index()
    {
     
       $this->load->library('pro'); // initialize the library
    echo $this->pro->show_me();
    }
   
   

}
?>

useing of your class

$this->load->library('pro'); // initialize the library
call you function create in library like this echo $this->pro->show_me();

check it result.

you can pass parameter in your library.

application/libraries/Pro.php create this function.

public function show_hello_world($param){
   
    if($param['color']=="red"){
     
       echo "hello World Red";
     
    }elseif($param['color']=="blue"){
     
       echo "Hello World blue";
     
    }else{
echo “Hello World”;
}

?>

here i am create show_hello_world function and Pass value $param.
check it your codeinter.

in Your test Controller. application\controllers\Test.php

function index()
    {
     
       $param = array("color"=>"blue");
       $this->load->library('pro');
     
                 $menu = new pro;
               
                 $data['menu'] = $menu->show_menu();
               
                 echo $data['menu'];
   
    }

No comments:

Post a Comment

Thank You For Comment