Welcome Guest, Not a member yet? Register   Sign In
Calling library method inside model error (with solution)
#1

Hi everyone,
I was spent a lot of time solving this situation in a my current project and I would like to share with all of you this solution to whom may help. 
It's a matter of calling a class method from model method called from a constructor without class being completely loaded. Probably Too trivial.. and for beginners but.. we do not always have a good day  Rolleyes

Suppose we have this case: 
(I apologize about wrong code, capitals, etc.. I have rewritten this code without testing it, but making it similar and removing useless information from my current project)


Controller mycontroller
-------------------------


Code:
class mycontroller extends CI_Controller() {
 function __construct() {
   parent::__construct();
   $this->load->library("folder/mylibrary");
 }
}


library mylibrary
-----------------

Code:
protected $obj;
class mylibrary() {
 function __construct() {
   $this->obj =& get_instance();
   $this->obj->load->model("folder/mymodel");
   $this->obj->load->library("folder/mysecondlibrary");
 }
}



library mysecondelibrary
-------------------------


Code:
class Mysecondlibrary{

 protected $obj;

function __construct() {
$this->obj = & get_instance();
$this->obj->mymodel->mymodelmethod();
}

function mymethod() {
return true;
}
}


model mymodel
-----------------

Code:
class Mymodel extends CI_Model {
        
    function __construct() {
        parent::__construct();
    }

   function mymodelmethod() {
       $this->mysecondlibrary->mymethod(); /* This crash: Undefined property: Mycontroller :: mylibrary Filepath: system\core\Model.php, [..]
   }
}



If we call a library method from model method which it was called from a library constructor class this will crash. We need to call method after
libraries are loaded.

To solve this, we need to call a class init method after loading.

library mylibrary
-----------------

Code:
protected $obj;
class mylibrary() {
 function __construct() {
    $this->obj =& get_instance();
    $this->obj->load->model("folder/mymodel");
    $this->obj->load->library("folder/mysecondlibrary");

    /** ADDED */
    $this->mysecondelibrary->init();
 }
}



library mysecondelibrary
-------------------------


Code:
class Mysecondlibrary{

  protected $obj;

  function __construct() {
    $this->obj = & get_instance();
   /** Mymodel Method call removed */
  }

  /** ADDED */
  function init() {
    $this->obj->mymodel->mymodelmethod();
   }

  function mymethod() {
    return true;
  }
}
Reply


Messages In This Thread
Calling library method inside model error (with solution) - by elche - 09-26-2018, 09:46 AM



Theme © iAndrew 2016 - Forum software by © MyBB