Saturday, 23 January 2016

Load All Varibales in every Controller Using Codeignter

This post for people know Codeignter been one year lah especially for me. This is about load same varibale each controller, please see script bellow

 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Welcome extends CI_Controller {  
 public function read1()  
   {  
  $data['notif']=$this->Notif_model->get_all_notif(); //same varibale  
  }  
 public function read2()  
   {  
  $data['notif']=$this->Notif_model->get_all_notif(); //same varibale  
  }  
 public function read3()  
   {  
  $data['notif']=$this->Notif_model->get_all_notif(); //same varibale  
  }  
 }  

as you can see there are same varibale in every function, that's not clean code i guess !
so idecide to search about this issue then i found it
  1. GLOBAL VARIBALE
  2. EXTENDS CONTROLLER
after few hours digging on global varibale hard to learn then i leave it, focus on extends controller from stackoverflow here, yes stackoverflow is the best place to throw fuckin stress.

Then i make extends controller 
 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class AppKaryawan extends CI_Controller  
 {  
  /**  
  * @return void  
  **/  
  function __construct()  
  {  
  parent::__construct();  
  //load variable global  
  $this->data = array(  
       'notif' => $this->Notif_model->get_all_notif()  
     );  
  if (($this->session->userdata('cu_level') === 'Pegawai') or ($this->session->userdata('cu_level') === 'Manajer'))   
  {  
   return TRUE;  
  }  
  else  
  {  
   //show_404(); // OR   
   redirect('login');  
   return FALSE;  
  }  
  }  
 }  


Please see my extends above only for level Manajer, but ignore it lah it doesn't important. then let see the controller after extends controller this is will change like this
 public function read1()  
   {  
  $data = $this->data;   
  }  
 public function read2()  
   {  
  $data = $this->data;   
  }  
 public function read3()  
   {  
  $data = $this->data;   
  }   

Please compare the controller, yes the second controller is really lite bite clean but after think and quit some minute it tottally same, wtf ! cause each function should write the $data, how can i make it more clean, i'm open disscuss guys !

if you any trick please throw the code so people will understanding, so i will reblog it again to make more clean, Thanks for visiting me !

Happy Weekend 

No comments:

Post a Comment