Devdatta Tengshe
Devdatta Tengshe

Reputation: 4075

How do I load Models in Child controller class & use in Parent class?

I'm trying to organize my Controllers & models, and moving common code to Parent classes. I've managed to organize my models, but am now stuck on organizing the controllers.

My Parent controller is:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
    protected $model;

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

    }

public function getDataByCity(){
    echo(json_encode($this->model->getDataByCity()));
}

}?>

My Child Controller is like this:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Hospital extends MY_Controller {

public function __construct(){
        parent::__construct();
      $this->load->model('hospital_model'); 
      //how do I load this into the Parent's $model variable?
    }
}
}?>

In my Child controller class, how do I load the particular model into the Parent's $model variable?

Upvotes: 1

Views: 308

Answers (3)

MAZux
MAZux

Reputation: 981

in MY_Controller:

class MY_Controller extends CI_Controller {
    protected $model;

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

    public function set_model($object)
    {
        $this->model = $object;
        $this->load->model($this->model);
    }

    public function getDataByCity(){
        echo(json_encode($this->model->getDataByCity()));
    }

}

in Hospital:

class Hospital extends MY_Controller {

    public function __construct(){
        parent::__construct();
        parent::set_model('hospital_model'); 
    }
}

Upvotes: 0

Alexander Popov
Alexander Popov

Reputation: 836

You can use the second parameter to assign your model to a different object name. However, $model property should be public.

Parent controller:

class MY_Controller extends CI_Controller {
    public $model;

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

    }

public function getDataByCity(){
    echo(json_encode($this->model->getDataByCity()));
}

}

Child controller:

class Hospital extends MY_Controller {

public function __construct(){
        parent::__construct();
      $this->load->model('hospital_model', 'model'); 
    }
}

Upvotes: 0

Arkadiusz G.
Arkadiusz G.

Reputation: 1086

in MY_Controller:

...
public function set_model($object)
{
    $this->model = $object;
}
...

in Hospital:

...
public function __construct(){
    parent::__construct();
  $this->load->model('hospital_model'); 
  parent::set_model($this->hospital_model);
}

...

Upvotes: 1

Related Questions