开发者

Load a model in a Codeigniter library

I have this piece of code:

class MY_Language extends CI_Language {

   function MY_Language()
   {
       parent::CI_Language();        

       $CI =& get_instance();

       $CI->load->model('langua开发者_StackOverflow社区ge_model');

       $languages = $this->language_model->get_languages();

       print_r($languages);
   }

}

But I keep getting "Fatal error: Call to undefined function get_instance() in C:\xampp\htdocs\application\libraries\MY_Language.php on line 44". Any ideas? Thanks in advance!


The framework creates the Language object prior to the CodeIgniter base object. So at that point in the code you won't yet be able to use the base object. In fact, the codeigniter/Base5.php file has yet to be included. This file defines the get_instance function. Thats why you are getting this particular error.

If you look in the codeigniter/CodeIgniter.php file you'll see that

$LANG =& load_class('Language');

comes prior to

require(BASEPATH.'codeigniter/Base5'.EXT);

Edit

Based on your comment below, I think you should be able to get an instance of the DB as follows. This was dug from the database function of the Loader class.

require_once BASEPATH.'database/DB'.EXT;
$db = DB('', false);


Stephen Curran way to load model from library is way to hard. You just only need to take your loaded model from CI instance.

$languages = $CI->language_model->get_languages();

but first you need to load database class first with normal load or autoload.

$this->load->database(); or $autoload['libraries'] = array('database');

and if you use autoload for loading your instance you should arrange it at right sequence.

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

with loaded model in your library $CI->load->model('language_model'), you actually already attach your model at CI instance. And you can easily get it from CI instance.


Suppose your class exists in application/libraries folder namely is field_validation.php and other class Name that exist in model namely Fields_model.php.

you need to following steps, create a public object name $ci in your library and in your library constructor , do the following steps.

  • Load CodeIgniter global object ($CI = & get_instance()).

  • From CodeIgniter global object you can access your model ($CI->load->model('Fields_model')).

  • Assigned CodeIgniter object to public variable , you can access the model function by ( $this->ci->Fields_model->applyValidation()).

  • Follow the example at bottom.

     class FieldValidation {
    
              public $ci;
    
              public function __construct() {
                 $CI = & get_instance();
                 $CI->load->model('Fields_model');
                 $this->ci = $CI;
             }
    
            public function applyValidation(){
    
               $this->ci->Fields_model->applyValidation();
    
          }
        }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜