【问题标题】:How can I use proper object-oriented models in CodeIgniter with constructors?如何在带有构造函数的 CodeIgniter 中使用正确的面向对象模型?
【发布时间】:2011-12-13 18:32:45
【问题描述】:

我目前创建 CodeIgniter 模型的方式是(即没有构造函数,必须一直传递 userID 并且仅限于一个对象):

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

但我想这样做:

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

更新:也许只是一个用户模型是一个糟糕的例子。

例如,如果我有一个包含各种物品的购物清单,我想以这种方式使用 PHP:

$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 在以这种方式处理 PHP OO 时感觉从根本上被破坏了。有没有人有任何解决方案仍然可以在每个模型中使用超级对象?

【问题讨论】:

  • 您只是喜欢使用新的运算符吗?
  • Codeigniter 使用一个名为 CI 的大型超级对象。我认为向该框架添加新对象不是一个好主意。无论如何,他们应该从他那里继承。
  • 我希望能够将对象存储在其他对象中
  • 您不应该对 CI 中每个对象的每个实例都使用 load-> 函数。它仅适用于应用程序级项目。没有什么能阻止您创建自己的对象(库或模型)并使用require_once 使它们可用,然后根据需要实例化/使用它们。如果您需要访问 CI 对象,您可以通过 $CI =& get_instance(); 从任何地方获取它

标签: php codeigniter model


【解决方案1】:

你可以像往常一样做:

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

或者,您可以依赖表级模型返回记录级模型:

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

同时,在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
}

【讨论】:

    【解决方案2】:

    您可以subclass 模型或在constructor 中添加一些内容 我认为您需要调整代码以按照您希望的方式进行操作……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-21
      • 2023-03-12
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 2019-11-05
      相关资源
      最近更新 更多