Friday, December 23, 2016

Create new and Extend native CodeIgniter library

Library is a class that is normally located in the libraries directory. There are several CodeIgniter libraries which you could extend if you simply need to add some functionality. CodeIgniter also permits you to replace native libraries just by placing identically named versions in your "application/libraries" directory.
In summary:
  • You can create new libraries.
  • You can extend native libraries.
  • You can replace native libraries with your own.
Note:
You can extend or replace all libraries except Database classes

Where to store libraries

Your library classes should be placed within your "application/libraries" directory.

Naming Conventions

  • File names must be capitalized. For example: Mylibraryclass.php
  • Class declarations must also be capitalized. Ex. class Mylibraryclass
  • Class names and file names must be the same

Basic Class Prototype

Your Classes should have this basic class prototype:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Yourclassname {

        public function your_method_name()
        {
        }
}
Normally you would call class method on your controller using $this construct. However, it only works within your controllers, your models, and on your views. If you would like to load your classes within your custom library, you would need to do the following:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
It is necessary to assign CodeIgniter object by reference since the value of CI_Controller::$instance is subject to change if another instance of the class is created.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Your_class_name {

        protected $CI;

        // We'll use a constructor, as you can't directly call a function
        // from a property definition.
        public function __construct()
        {
                // Assign the CodeIgniter super-object
                $this->CI =& get_instance();
        }

        public function foo()
        {
                $this->CI->load->helper('url');
                redirect();
        }

        public function bar()
        {
                echo $this->CI->config->item('base_url');
        }

}

As an example, we will be creating a simple library that would validate our form inputs. Simple enough, create a new file in your "app/libraries" directory and name it as "Profilevalidation.php"
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Profilevalidation {

    function __construct()
    {
        $this->_ci =& get_instance();
        
        $this->_ci->load->library('form_validation');
        $this->_ci->form_validation->set_error_delimiters('<span class="has-error">', '</span>');
    }
    
    public function valid_profile() {
        $ci = &get_instance();
        $ci->form_validation
            ->set_rules('fname', 'First Name','trim|required' )
            ->set_rules('mname', 'Middle Name','trim|required' )
            ->set_rules('lname', 'Last Name','trim|required' );
        return $ci->form_validation->run();
    }
    

}
We just created a new simple library which validates user inputs. We then need to load the newly created library in our controller.
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Settings extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->library('profile_model'); 
        $this->load->library('profilevalidation'); 
    }
    public function update_profile() {
 $response = array();
        $response['status'] = 'error';
 if( $this->profilevalidation->valid_profile() )
        {
  $profile_info = array(
      'fname'=>$this->input->post('fname'),
      'mname'=>$this->input->post('mname'),
      'lname'=>$this->input->post('lname')
  );
  $this->trans_begin();
  $this->profile_model->update($user_id, $profile_info);
  if($this->trans_status()){
   $response['status'] = 'success';
                 $response['message'] = 'Profile has been successfully updated';
  }
  else{
   $response['status'] = 'error';
                 $response['message'] = 'Something went wrong, please try again.';
  }
 }
 else{
     $response['status'] = 'form-incomplete';
     $response['message'] = 'Please check all fields and try again';
            $response['error_fields'] = $this->form_validation->error_assoc();
            $response['error_messages'] = validation_errors();
 }
 echo json_encode($response);
    }
The above controller loads the newly created library where we set our validation rules. We could easily validate our profile form in multiple controllers just by loading and calling our library function just like what you would normally do in other native CodeIgniter classes.

Extending Native Libraries

If all you need is an additional functionality to an existing library, then it's overkill to re-code or replace the existing library with your own. Simply extend the existing library by doing the following:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Email extends CI_Email {

}
Note:
  • The class declaration must extend the parent class.
  • Your new class name and filename must be prefixed with MY_.
By default, your subclass prefix is 'MY_'. To set your own sub-class prefix, open your "application/config/config.php" file and look for the following line:
$config['subclass_prefix'] = 'MY_';
Please take note that "CI_" is already being used by CodeIgniter libraries thus use different one.

1 comment:

  1. Hello World !
    Good Day !

    Keep you services updated & reliable with my stuff
    Huge stuff of Tools, E-boooks, Tutorials, Scripting, Viruses, Spying e.t.c

    See Me On
    I C Q :> 752822040
    Tele-Gram :> @killhacks

    Many other stuff like
    SSN/DL
    ID's
    CC CVV
    DUMPS
    Combos/I.P's/Proxies
    You can get from my collections :-)

    No one TEACH you
    No one GUIDE you
    No one BOOST you
    But I'm always here for you

    Hit me up for you desired stuff
    I C Q here :> 752822040
    Tele-Gram here :> @killhacks

    %Waiting for you guys%

    ReplyDelete