PHP 中的工厂类,没有 __construct?我使用什么方法名称?

发布于 2024-09-09 08:17:34 字数 308 浏览 7 评论 0原文

我有一个用 PHP 制作的工厂类。每个实例代表数据库表中的一行。

由于我将处理数十个数据库行,因此让每个实例在实例化时进行选择是愚蠢的。因此,我有一种方法可以将值转储到对象中,以便与返回大量行的数据库查询结合使用。

但有时,我还想让对象查找查询中的所有值。因此,我将采用另一种方法,该方法将主键作为参数,并从数据库查询中查找值。

所以看来在这两种方法之间,我真的不需要 __construct 方法。

这种类型的模式有没有比“工厂”更具体的名称?我应该如何称呼这两种不同的构造对象方法——这些方法有常用的名称吗?

I have a factory class I'm making in PHP. Each instance represents a row from a database table.

Since I'll be dealing with dozens of database rows, it would be silly to have each instance do a select on instantiation. So I have a method to just dump values in to the object, for use in conjunction with a database query that returns a lot of rows.

But from time to time, I'll also want to have the object look up all the values in a query. So, I'll have another method that takes the primary key as an argument, and looks up the values from a database query.

So it seems that between these two methods, I won't really need a __construct method.

Is there a name for this type of pattern, more specific than 'factory'? What should I call these two different methods for constructing the object -- are there commonly used names for these methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月如刀 2024-09-16 08:17:34

我认为您的模式有点类似于表数据网关

由于它需要访问数据库,我建议给它一个构造函数。您可以向构造函数传递数据库对象(例如,PDO,如果您使用它,或其他),因此该类不需要知道如何连接到数据库。

否则你的想法似乎不错。

I think the pattern you have is somewhat similar to the table data gateway.

Since it needs access to the database, I would recommend giving it a constructor. You can pass the constructor the database object (eg. PDO if you use it, or others), so the class does not need to know how to connect to the database.

Otherwise your idea seems good.

美煞众生 2024-09-16 08:17:34

也许除了数据类之外您还需要 DAO 存储类?

<?php
class Row {
  private $fields1;
  private $fields2;
  __construct($field1, $field2) {
    $this->fields1 = $fields1;
    $this->fields2 = $fields2;
  }
}

class Storage {
  public load($id) {
    $rawRow; // loaded from db
    return $this->createRow($rawRow);
  }
  protected createRow(array $rawRow) {
    return new Row($rawRow['fields1'], $rawRow['fields2']);
  }
}
?>

Maybe you need a DAO storage class in addition to your data class?

<?php
class Row {
  private $fields1;
  private $fields2;
  __construct($field1, $field2) {
    $this->fields1 = $fields1;
    $this->fields2 = $fields2;
  }
}

class Storage {
  public load($id) {
    $rawRow; // loaded from db
    return $this->createRow($rawRow);
  }
  protected createRow(array $rawRow) {
    return new Row($rawRow['fields1'], $rawRow['fields2']);
  }
}
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文