Result.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\data\source\database\adapter\pdo;
  9. use PDO;
  10. use PDOStatement;
  11. use PDOException;
  12. /**
  13. * This class is a wrapper around the MySQL result returned and can be used to iterate over it.
  14. *
  15. * It also provides a simple caching mechanism which stores the result after the first load.
  16. * You are then free to iterate over the result back and forth through the provided methods
  17. * and don't have to think about hitting the database too often.
  18. *
  19. * On initialization, it needs a `PDOStatement` to operate on. You are then free to use all
  20. * methods provided by the `Iterator` interface.
  21. *
  22. * @link http://php.net/manual/de/class.pdostatement.php The PDOStatement class.
  23. * @link http://php.net/manual/de/class.iterator.php The Iterator interface.
  24. */
  25. class Result extends \lithium\data\source\Result {
  26. public $named = false;
  27. /**
  28. * Fetches the result from the resource and caches it.
  29. *
  30. * @return boolean Return `true` on success or `false` if it is not valid.
  31. */
  32. protected function _fetchFromResource() {
  33. if ($this->_resource instanceof PDOStatement) {
  34. try {
  35. $mode = $this->named ? PDO::FETCH_NAMED : PDO::FETCH_NUM;
  36. if ($result = $this->_resource->fetch($mode)) {
  37. $this->_key = $this->_iterator;
  38. $this->_current = $this->_cache[$this->_iterator++] = $result;
  39. return true;
  40. }
  41. } catch (PDOException $e) {}
  42. }
  43. $this->_resource = null;
  44. return false;
  45. }
  46. public function __destruct() {
  47. $this->close();
  48. }
  49. }
  50. ?>