简体   繁体   English

PHP OOP数据库结果

[英]PHP OOP Database Results

I'm having trouble getting my head around a concept with PHP and OOP. 我很难理解PHP和OOP的概念。 Say I have a class, years, which matches up with years in a database. 假设我有一个班级,年份,它与数据库中的年份匹配。 I'm using PDO to connect with the database and perform queries. 我正在使用PDO连接数据库并执行查询。 At the moment it's designed so that the years class also contains a method called 'getAllYears' which does the SQL query to get all years in the format I want. 目前,它已被设计为,Years类还包含一个名为“ getAllYears”的方法,该方法执行SQL查询以获取我想要的格式的所有年份。 The problem I then have is how to loop through all the years, whilst making sure I can access them from the years class. 然后,我的问题是如何遍历所有年份,同时确保可以从Years类访问它们。 For instance I would like to call this: 例如,我想这样称呼:

$years->getAllYears()

and then loop through them in the body of my application referencing them like this: 然后在我的应用程序主体中遍历它们,如下所示:

$years->yearID; $years->yearName;

etc. 等等

Am I missing something fundamental about OOP (perhaps splitting up the getting everything from the database year, and the object that is returned) or is there a way of doing this? 我是否缺少有关OOP的基本知识(也许是从数​​据库年度中获取所有内容以及返回的对象),还是有办法做到这一点?

If $years->getAllYears() returns iterable and yearID and yearName are both properties of single item, then just do this: 如果$years->getAllYears()返回iterable并且yearIDyearName都是单个项目的属性,则只需执行以下操作:

foreach ($years->getAllYears() as $year) {
    // use it, $year is now a single instance
    echo $year->yearID;
    echo $year->yearName;
}

If you are asking about how to make getAllYears() be iterable over appropriate instances, take a look at this: 如果您询问如何使getAllYears()在适当的实例上可迭代,请查看以下内容:

  • Iterator interface - allowing you to iterate over anything without the need to make it array first (and thanks to that, you do not need to process it all at once and store the results in the memory); Iterator接口 -允许您迭代任何东西而无需首先使其成为数组(因此,您无需一次全部处理并将结果存储在内存中); in PHP 5.5 and later you can use generator syntax , 在PHP 5.5及更高版本中,您可以使用生成器语法
  • PDOStatement::fetchObject() - allows you to fetch object from the PDO statement, and you are able to set class for it, PDOStatement::fetchObject() -允许您从PDO语句中获取对象,并且可以为其设置类,

These elements combined (iterator fetching next object of specific class with every iteration) will give you what you want. 这些元素组合在一起(迭代器在每次迭代中都提取特定类的下一个对象)将为您提供所需的内容。 Also, this very closely resembles some existing ORMs, so you may wish to take a look at them: eg. 另外,这与某些现有的ORM非常相似,因此您不妨查看一下它们: Zend's ORM has distinction between classes representing table and row (see here ). Zend的ORM在表示表和行的类之间有所区别(请参阅此处 )。

To supplement on @Tadeck answer, specifically the comment section on how to implement a traversable object. 为了补充@Tadeck的答案,特别是关于如何实现可遍历对象的注释部分。 The reason why I mentioned stdClass was specifically due to PDOs ability that PDOStatement implements the Traversable interface. 为什么我提到的原因stdClass是特别是由于PDO的能力是PDOStatement对象实现Traversable的接口。 This means that the PDOStatement instance (returned by PDO::query() and PDO::prepare() ) can be used in array featured functions like foreach (as of PHP 5.1). 这意味着PDOStatement实例(由PDO :: query()PDO :: prepare()返回 )可以在诸如foreach数组功能函数中使用(从PHP 5.1开始)。

The method getAllYears should therefor not be implemented by any stdClass . 因此,任何stdClass都不应实现getAllYears方法。 The only function getAllYears should have is prepare and return a PDOStatement instance initiated to return each row result as an object (therefor the use of stdClass as an anonymous object) in order to be used in the foreach example (using the object operator as in $year->yearID ). getAllYears唯一应具有的功能是准备并返回一个PDOStatement实例,该实例启动getAllYears返回的每一行结果作为一个对象(因此将stdClass用作匿名对象),以便在foreach示例中使用(使用object operator$year->yearID )。

The OP Years class would have a method called getAllYears() which queries the results. OP Years类将具有一个名为getAllYears()的方法来查询结果。 Implementation example : 实施示例

// an example of the Years class implementing getAllYears
class Years {

  public function getAllYears() {
    // pseudo variable representing your original PDO object 
    // being used somehow.
    $conn = new PDO();

    // prepare a statement selecting all years
    $stmt = $conn->prepare(" select all years ");

    // set the fetch mode to return an anonymous object,
    // mapping column names to properties, on each iteration
    $stmt->setFetchMode(PDO::FETCH_OBJ);

    // return the statement if no SQL errors occurred
    // implement the way you would handle any SQL errors
    if(!$stmt->execute())
      throw new Exception('exception thrown: SQL error');

    return $stmt;
  }
}

Demo: 演示:

$Years = new Years;
// the PDOStatement returned can be immediately used for iteration
foreach($Years->getAllYears() as $year) {
  // $year represents an anonymous object, each column is a property
  // of this object
  $year->yearID;
  $year->yearName;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM