在Code ignition中似乎不可能将变量传递给Model的构造函数。也许我在MVC或Code Igniter中错过了一些东西,但我不明白是什么。
在我的情况下,我应该使用库而不是模型吗?(库实际上接受形参)实际上我的代码是这样的,我觉得有点奇怪:
控制器:
class User extends CI_Controller {
public function user($user_id) {
$this->load->model('user');
$this->user->setId($user_id);
$data['username'] = $this->user->getName();
// Isn't it a bit strange ? I can load the class User even if the User doesn't mean anything ?
}
}
模型:
class User extends CI_Model {
private $id;
private $name;
public function setId($id) {
$this->id = $id;
// Retrieve data from DB...
$this->name = $retrieved_data['name'];
}
public function getName() {
return $this->name;
}
}
试试这个:
控制器:
class User extends CI_Controller {
public function user($user_id) {
$this->load->model('user_model');
$data['username'] = $this->user_model->getName($user_id);
}
}
模型:
class User_model extends CI_Model {
public function getName($user_id) {
//Retrieve data from DB using the $user_id variable...
return $retrieved_data['name'];
}
}
似乎是一种更合乎逻辑和更快的方法。不确定它是否符合您的代码的其余部分,但它可能有助于您跟踪错误。