我试图组织我的控制器和放大器模型,并将公共代码移动到父类。我设法组织了我的模型,但现在我不得不组织控制器。
我的父控制器是:
<?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()));
}
}?>
我的孩子控制器是这样的:
<?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?
}
}
}?>
在我的Child控制器类中,如何将特定模型加载到Parent的$ model变量中?
答案 0 :(得分:1)
:
...
public function set_model($object)
{
$this->model = $object;
}
...
在医院:
...
public function __construct(){
parent::__construct();
$this->load->model('hospital_model');
parent::set_model($this->hospital_model);
}
...
答案 1 :(得分:0)
您可以使用第二个参数将模型分配给其他对象名称。但是,$model
属性应为public
。
家长控制器:
class MY_Controller extends CI_Controller {
public $model;
public function __construct(){
parent::__construct();
}
public function getDataByCity(){
echo(json_encode($this->model->getDataByCity()));
}
}
儿童控制器:
class Hospital extends MY_Controller {
public function __construct(){
parent::__construct();
$this->load->model('hospital_model', 'model');
}
}
答案 2 :(得分:0)
:
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()));
}
}
在医院:
class Hospital extends MY_Controller {
public function __construct(){
parent::__construct();
parent::set_model('hospital_model');
}
}