dongrong9053 2011-12-13 18:32
浏览 41
已采纳

如何在CodeIgniter中使用适当的面向对象模型和构造函数?

The way I create CodeIgniter models at the moment is (i.e. no constructor, having to pass userID all the time and limited to one object):

$this->load->model('User');
$this->user->set_password($userID, $password);

But I would like to do it like this:

$this->load->model('User');
$User = new User($userID);
$User->set_password($password);

UPDATE: Perhaps just a user model was a poor example.

For instance, if I have a shopping list that has various items I would like to use PHP in this way:

$this->load->model('List');
$this->load->model('Item');

$List = new List();
$items[] = new Item($itemName1, $itemPrice1);
$items[] = new Item($itemName2, $itemPrice2);

$List->add_items($items);

CodeIgniter feels fundamentally broken in handling PHP OO in this way. Does anyone have any solutions that can still use the superobject within every model?

  • 写回答

2条回答 默认 最新

  • douju7765 2011-12-13 18:43
    关注

    You can do it like you normally would:

    require_once(APPPATH.'models/User.php');
    $User = new User($userID);
    

    Or, you can rely on a table-level model to return a record-level model:

    $this->load->model('users_model'); // users (plural) is the table-level model
    $User = $this->users_model->get_user($userID);
    

    Meanwhile, in users_model

    require_once(APPPATH.'models/User.php');
    
    public function get_user($userID)
    {
      // get a record from the db
      // map record to model
      // return model
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?