Welcome Guest, Not a member yet? Register   Sign In
Extending models by several levels
#1

[eluser]kimp[/eluser]
I'm trying to extend a model several levels. I have read the user guide, and this post http://ellislab.com/forums/viewthread/134164/, but am still running in to trouble.

I have created MY_model and stored it in the app/libraries directory. I then create A_model, and store it in app/models. A_model extends MY_model, and when I load it in a controller it works fine.

I then create B_model which extends A_model, and this is where I run into trouble. If I try to load B_model while A_model is in the apps/libraries directory, I get the CI error "An Error Was Encountered". If I move A_model back to the models directory, I get an Apache 500 Internal Server Error.

The reason that I am trying to do this is that I have a game with two types of players (real entities and pseudo entities). Players will be my A_model, with Real Entites as my B_model (and Pseudo Entities as a C_Model, which will also extend A_model).

Any help appreciated!
#2

[eluser]Phil Sturgeon[/eluser]
CodeIgniter does not support true PHP5 autoloading, in the sense that you cannot use a class just by calling its name. You need to include the file for a class somehow before you can use or inherit it.

A_model extends MY_Model is done out of the box when you load A_model as MY_Model will be automatically loaded by the Loader library. The problem is when you load B_Model. If you A after B then everything will be fine, but if you load B without loading A then CodeIgniter (and PHP in general) will have no idea that the class exists.

You could add this line in class B:

Code:
<?php
include_once APPPATH . 'models/A_model.php';
class B_model extends A_model {

Or you could create an autoload function:

Code:
function __autoload($class)
{
    if(strpos($class, 'CI_') !== 0)
    {
        if($file = APPPATH . 'core/'. $class . '.php')
        {
            include_once $file;
        }
        
        else if($file = APPPATH . 'libraries/'. $class . '.php')
        {
            include_once $file;
        }
        
        else if($file = APPPATH . 'models/'. $class . '.php')
        {
            include_once $file;
        }
    }
}

That will help you get base classes working for your controllers too.
#3

[eluser]kimp[/eluser]
Thanks Phil,

This was super helpful.

For others, note there is a typo where the 'if' statements are. For example, the:

Quote:if($file = APPPATH . 'libraries/'. $class . '.php')

Should have a 'file exists' such as:

Code:
if(file_exists($file = APPPATH . 'libraries/'. $class . '.php'))




Theme © iAndrew 2016 - Forum software by © MyBB