2013-02-03 20 views
0

我開發了一個接口和類來屏蔽PDOStatement。如果我實現了一個Iterator類來封裝一個PDOStatement,key()方法應該做什麼

接口:

interface ResultSetInterface extends Iterator 
{ 
    public function count(); 
    public function all(); 
} 

類:

class ResultSet implements ResultSetInterface 
{ 
    /** 
    * @var PDOStatement 
    */ 
    protected $pdoStatement; 

    protected $cursor = 0; 

    protected $current = null; 

    private $count = null; 

    public function __construct($pdoStatement) 
    { 
     $this->pdoStatement= $pdoStatement; 
     $this->count = $this->pdoStatement->rowCount(); 
    } 

    public function rewind() 
    { 
     if ($this->cursor > 0) { 
      throw new Exception('Rewind is not possible'); 
     } 
     $this->next(); 
    } 

    public function valid() 
    { 
     return $this->cursor <= $this->count; 
    } 

    public function next() 
    { 
     $this->current = $this->pdoStatement->fetch(); 
     $this->cursor++; 
    } 

    public function current() 
    { 
     return $this->current; 
    } 

    public function key() 
    { 
    } 

    public function count() 
    { 
     return $this->count; 
    } 

    public function all() { 
     $this->cursor = $this->count(); 
     return $this->pdoStatement->fetchAll(); 
    } 
} 

這工作得很好。但我不知道如何使用實現Iterator類所需的key()方法。有任何想法嗎?

+0

'return $ this-> cursor;'? –

+0

謝謝,關鍵會用在什麼時候? –

+1

http://php.net/manual/en/class.iterator.php這裏的第一個例子顯示了每個函數何時被使用。 –

回答

2

首先,關於您的界面,我認爲您最好擴展CountableIterator,因爲您想添加count()方法,並且在SPL中有一個用於此目的的神奇界面。

關鍵的方法。你必須記住,在PHP中,每個可迭代的內容都是一個關鍵字和一個值的關聯。它從PHP數組繼承而來。

迭代器是一種重載foreach運算符的方法,並且作爲由foreach($iterator as $key=>$value)組成的sythax,您必須給出關鍵方法實現。

你的情況,你有兩個解決方案:

  • 使用$pdo->cursor
  • 創建名爲$ currentKey自己的屬性,並在每次使用next方法時,加一。
+0

謝謝你,我會檢查CountableIterator –

相關問題