简体   繁体   中英

PHP OOP Database Results

I'm having trouble getting my head around a concept with PHP and 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. 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. The problem I then have is how to loop through all the years, whilst making sure I can access them from the years class. 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?

If $years->getAllYears() returns iterable and yearID and yearName are both properties of single item, then just do this:

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:

  • 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); in PHP 5.5 and later you can use generator syntax ,
  • PDOStatement::fetchObject() - allows you to fetch object from the PDO statement, and you are able to set class for it,

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. Zend's ORM has distinction between classes representing table and row (see here ).

To supplement on @Tadeck answer, specifically the comment section on how to implement a traversable object. The reason why I mentioned stdClass was specifically due to PDOs ability that PDOStatement implements the Traversable interface. 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).

The method getAllYears should therefor not be implemented by any stdClass . 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 ).

The OP Years class would have a method called getAllYears() which queries the results. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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