Extends Model in CodeIgniter

2019-02-18 21:08发布

问题:

Well, I'm newbie in CodeIgniter Framework and i'm trying building a generic Model Class. See:

class Basic_Model extends CI_MODEL {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

}

I want to extends all Models based on Basic_Model, like this:

class Pagina_Model extends Basic_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

}

The problem is when i try to call "pagina_model" from a Controller a got the following error:

Fatal error: Class 'Basic_Model' not found in /var/www/myproject/application/models/pagina_model.php on line 12

If i use "basic_model" in controller everything works fine.

EDIT 1:

I created a file named MY_Basic_Model.php in "/application/core" and changed the class name to "MY_Basic_Model". But i got the error:

Fatal error: Class 'MY_Basic_Model' not found in /var/www/myproject/application/models/pagina_model.php on line 12

回答1:

For this you have to create Core System Classes (this is also known as Method Overriding).

Create a file MY_Model.php in application/core/ directory which will extend the base CI_Model class:

<?php
class MY_Model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
}

Now you can extend this in your models (../applicaton/models/):

<?php
class Pagina_Model extends MY_Model {

    function __construct()
    {
        parent::__construct();
    }
}


Few things to note here:
1) The class declaration must extend the parent class.
2) Your new class name and filename must be prefixed with MY_ (this item is configurable).


How to configure:
To set your own sub-class prefix, open your application/config/config.php file and look for this item:

$config['subclass_prefix'] = 'MY_';


Documentation:
https://ellislab.com/codeigniter/user-guide/general/core_classes.html



回答2:

You can do it this way.
lets assume you have basic_model.php inside your model folder . Now add the code for class Basic_Model that you have written

class Basic_Model extends CI_MODEL {

  function __construct() {
    // Call the Model constructor
    parent::__construct();
  }

}

Now make a pagina_model.php inside your model folder and add the code that you written. Just include the first line like bellow

<?php
  require APPPATH.'/models/basic_model.php';//just add this line and keep rest 
  class Pagina_Model extends Basic_Model {

      function __construct()
      {
          parent::__construct();
      }
   }

hope this will solve your problem



回答3:

You can do this ... MY_ model is really good but should you wish a sub model to extend a different sub model you can always do:

require(APPPATH.'models/Other_model.php');
class New_model extends Other_Model {

In my instance Other_Model actually extends MY_model.