How to Access a Model from another Model
Accessing models from another model is one question that you hear a lot from new CodeIgniter users. It's actually quite easy and somewhat like loading a user created library in CodeIgniter.
A pretty straightforward way to include a model from within another model is to instantiate it from within:
class Project_model extends Model {
function Project_model()
{
parent::Model();
}
function save()
{
$service = new Service_model;
$service->get_services();
}
}
However the above code isn't so efficient as it creates a object in memory. It's much better to use CodeIgniter's get_instance() for less memory usage:
class Project_model extends Model {
function Project_model()
{
parent::Model();
}
function save()
{
$CI =& get_instance();
$CI->load->model('service_model');
$CI->service_model->get_services();
}
}
Categories: How To, Web Development
Tags: codeigniter, models
No Comments