Result.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace PHPixie\DB;
  3. /**
  4. * Allows to access database results in a unified way and
  5. * provides iterator support, so it can be used inside loops like 'foreach'
  6. * @package Database
  7. */
  8. abstract class Result implements \Iterator
  9. {
  10. /**
  11. * Current row number
  12. * @var integer
  13. */
  14. protected $_position = -1;
  15. /**
  16. * Database result object
  17. * @var mixed
  18. */
  19. protected $_result;
  20. /**
  21. * Current row
  22. * @var object
  23. */
  24. protected $_row;
  25. /**
  26. * If at least one row has been fetched
  27. * @var object
  28. */
  29. protected $_fetched = false;
  30. /**
  31. * Returns current row
  32. *
  33. * @return object Current row in result set
  34. */
  35. public function current()
  36. {
  37. $this->check_fetched();
  38. return $this->_row;
  39. }
  40. /**
  41. * Gets the number of the current row
  42. *
  43. * @return integer Row number
  44. */
  45. public function key()
  46. {
  47. $this->check_fetched();
  48. return $this->_position;
  49. }
  50. /**
  51. * Check if current row exists.
  52. *
  53. * @return bool True if row exists
  54. */
  55. public function valid()
  56. {
  57. $this->check_fetched();
  58. return $this->_row != null;
  59. }
  60. /**
  61. * Returns all rows as array
  62. *
  63. * @return array Array of rows
  64. */
  65. public function as_array()
  66. {
  67. $arr = array();
  68. foreach ($this as $row)
  69. {
  70. $arr[] = $row;
  71. }
  72. return $arr;
  73. }
  74. /**
  75. * Checks if the rows from the result set have
  76. * been fetched at least once. If not fetches first row.
  77. *
  78. */
  79. protected function check_fetched()
  80. {
  81. if (!$this->_fetched)
  82. {
  83. $this->_fetched = true;
  84. $this->next();
  85. }
  86. }
  87. /**
  88. * Gets a column from the current row in the set
  89. *
  90. * @param string $column Column name
  91. * @return mixed Column value
  92. */
  93. public function get($column)
  94. {
  95. if ($this->valid() && isset($this->_row->$column))
  96. {
  97. return $this->_row->$column;
  98. }
  99. }
  100. }