0

PDOStatement を保護するためのインターフェイスとクラスを開発しました。

インターフェース:

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() メソッドの使用方法がわかりません。何か案は?

4

1 に答える 1

2

まずインターフェースについてですがCountableIterator、メソッドを追加したいので拡張した方がいいと思いますcount()し、SPLにはそのための魔法のインターフェースがあります。

キー方式について。PHP では、反復可能なすべてのコンテンツがキーと値の関連付けであることを覚えておく必要があります。PHP 配列から継承されます。

イテレータは、foreach演算子をオーバーロードする方法であり、 foreach はforeach($iterator as $key=>$value)、キーメソッドの実装を提供する必要があるときに構成されるシンタックスと同様です。

あなたの場合、2つの解決策があります:

  • を使用して$pdo->cursor
  • $currentKey という独自の属性を作成し、メソッドを使用するたびに増分しますnext
于 2013-02-03T10:02:56.150 に答える