Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extends Model in CodeIgniter

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
like image 898
Shelly Avatar asked Dec 01 '22 00:12

Shelly


2 Answers

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

like image 119
Parag Tyagi Avatar answered Dec 04 '22 08:12

Parag Tyagi


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

like image 42
oldlearner Avatar answered Dec 04 '22 09:12

oldlearner