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 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错