目次
1. モード定義
2. UML クラス図
3. サンプルコード
Book.php
BookList.php
BookListIterator.php
BookListReverseIterator.php
4. テストコード
Tests/IteratorTest.php
ホームページ バックエンド開発 PHPチュートリアル PHP デザイン パターン シリーズ -- イテレータ パターン (イテレータ)

PHP デザイン パターン シリーズ -- イテレータ パターン (イテレータ)

Jun 20, 2016 pm 12:41 PM

1. モード定義

イテレーター モード (Iterator)、カーソル (Cursor) モードとも呼ばれます。オブジェクトの内部詳細を公開せずに、コンテナ オブジェクト内の個々の要素にアクセスする方法を提供します。

集約オブジェクトにアクセスする必要があり、オブジェクトがどのようなものであってもそれを走査する必要がある場合は、反復子パターンの使用を検討する必要があります。さらに、複数の方法でコレクションを走査する必要がある場合は、反復子パターンの使用を検討できます。イテレータ パターンは、開始、次、終了するかどうか、現在の項目など、さまざまなコレクション構造をトラバースするための統一インターフェイスを提供します。

PHP 標準ライブラリ (SPL) は、反復子インターフェイス Iterator を提供します。反復子パターンを実装するには、このインターフェイスを実装するだけです。

2. UML クラス図

3. サンプルコード

Book.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class Book{    private $author;    private $title;    public function __construct($title, $author)    {        $this->author = $author;        $this->title = $title;    }    public function getAuthor()    {        return $this->author;    }    public function getTitle()    {        return $this->title;    }    public function getAuthorAndTitle()    {        return $this->getTitle() . ' by ' . $this->getAuthor();    }}
ログイン後にコピー

BookList.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class BookList implements \Countable{    private $books;    public function getBook($bookNumberToGet)    {        if (isset($this->books[$bookNumberToGet])) {            return $this->books[$bookNumberToGet];        }        return null;    }    public function addBook(Book $book)    {        $this->books[] = $book;    }    public function removeBook(Book $bookToRemove)    {        foreach ($this->books as $key => $book) {            /** @var Book $book */            if ($book->getAuthorAndTitle() === $bookToRemove->getAuthorAndTitle()) {                unset($this->books[$key]);            }        }    }    public function count()    {        return count($this->books);    }}
ログイン後にコピー

BookListIterator.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class BookListIterator implements \Iterator{    /**     * @var BookList     */    private $bookList;    /**     * @var int     */    protected $currentBook = 0;    public function __construct(BookList $bookList)    {        $this->bookList = $bookList;    }    /**     * Return the current book     * @link http://php.net/manual/en/iterator.current.php     * @return Book Can return any type.     */    public function current()    {        return $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Move forward to next element     * @link http://php.net/manual/en/iterator.next.php     * @return void Any returned value is ignored.     */    public function next()    {        $this->currentBook++;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Return the key of the current element     * @link http://php.net/manual/en/iterator.key.php     * @return mixed scalar on success, or null on failure.     */    public function key()    {        return $this->currentBook;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Checks if current position is valid     * @link http://php.net/manual/en/iterator.valid.php     * @return boolean The return value will be casted to boolean and then evaluated.     *       Returns true on success or false on failure.     */    public function valid()    {        return null !== $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Rewind the Iterator to the first element     * @link http://php.net/manual/en/iterator.rewind.php     * @return void Any returned value is ignored.     */    public function rewind()    {        $this->currentBook = 0;    }}
ログイン後にコピー

BookListReverseIterator.php

<?phpnamespace DesignPatterns\Behavioral\Iterator;class BookListReverseIterator implements \Iterator{    /**     * @var BookList     */    private $bookList;    /**     * @var int     */    protected $currentBook = 0;    public function __construct(BookList $bookList)    {        $this->bookList = $bookList;        $this->currentBook = $this->bookList->count() - 1;    }    /**     * Return the current book     * @link http://php.net/manual/en/iterator.current.php     * @return Book Can return any type.     */    public function current()    {        return $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Move forward to next element     * @link http://php.net/manual/en/iterator.next.php     * @return void Any returned value is ignored.     */    public function next()    {        $this->currentBook--;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Return the key of the current element     * @link http://php.net/manual/en/iterator.key.php     * @return mixed scalar on success, or null on failure.     */    public function key()    {        return $this->currentBook;    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Checks if current position is valid     * @link http://php.net/manual/en/iterator.valid.php     * @return boolean The return value will be casted to boolean and then evaluated.     *       Returns true on success or false on failure.     */    public function valid()    {        return null !== $this->bookList->getBook($this->currentBook);    }    /**     * (PHP 5 >= 5.0.0)<br/>     * Rewind the Iterator to the first element     * @link http://php.net/manual/en/iterator.rewind.php     * @return void Any returned value is ignored.     */    public function rewind()    {        $this->currentBook = $this->bookList->count() - 1;    }}
ログイン後にコピー

4. テストコード

Tests/IteratorTest.php

<?phpnamespace DesignPatterns\Behavioral\Iterator\Tests;use DesignPatterns\Behavioral\Iterator\Book;use DesignPatterns\Behavioral\Iterator\BookList;use DesignPatterns\Behavioral\Iterator\BookListIterator;use DesignPatterns\Behavioral\Iterator\BookListReverseIterator;class IteratorTest extends \PHPUnit_Framework_TestCase{    /**     * @var BookList     */    protected $bookList;    protected function setUp()    {        $this->bookList = new BookList();        $this->bookList->addBook(new Book('Learning PHP Design Patterns', 'William Sanders'));        $this->bookList->addBook(new Book('Professional Php Design Patterns', 'Aaron Saray'));        $this->bookList->addBook(new Book('Clean Code', 'Robert C. Martin'));    }    public function expectedAuthors()    {        return array(            array(                array(                    'Learning PHP Design Patterns by William Sanders',                    'Professional Php Design Patterns by Aaron Saray',                    'Clean Code by Robert C. Martin'                )            ),        );    }    /**     * @dataProvider expectedAuthors     */    public function testUseAIteratorAndValidateAuthors($expected)    {        $iterator = new BookListIterator($this->bookList);        while ($iterator->valid()) {            $expectedBook = array_shift($expected);            $this->assertEquals($expectedBook, $iterator->current()->getAuthorAndTitle());            $iterator->next();        }    }    /**     * @dataProvider expectedAuthors     */    public function testUseAReverseIteratorAndValidateAuthors($expected)    {        $iterator = new BookListReverseIterator($this->bookList);        while ($iterator->valid()) {            $expectedBook = array_pop($expected);            $this->assertEquals($expectedBook, $iterator->current()->getAuthorAndTitle());            $iterator->next();        }    }    /**     * Test BookList Remove     */    public function testBookRemove()    {        $this->bookList->removeBook($this->bookList->getBook(0));        $this->assertEquals($this->bookList->count(), 2);    }}
ログイン後にコピー
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

11ベストPHP URLショートナースクリプト(無料およびプレミアム) 11ベストPHP URLショートナースクリプト(無料およびプレミアム) Mar 03, 2025 am 10:49 AM

多くの場合、キーワードと追跡パラメーターで散らかった長いURLは、訪問者を阻止できます。 URL短縮スクリプトはソリューションを提供し、ソーシャルメディアやその他のプラットフォームに最適な簡潔なリンクを作成します。 これらのスクリプトは、個々のWebサイトにとって価値があります

Instagram APIの紹介 Instagram APIの紹介 Mar 02, 2025 am 09:32 AM

2012年のFacebookによる有名な買収に続いて、Instagramはサードパーティの使用のために2セットのAPIを採用しました。これらはInstagramグラフAPIとInstagram Basic Display APIです。

Laravelでフラッシュセッションデータを使用します Laravelでフラッシュセッションデータを使用します Mar 12, 2025 pm 05:08 PM

Laravelは、直感的なフラッシュメソッドを使用して、一時的なセッションデータの処理を簡素化します。これは、アプリケーション内に簡単なメッセージ、アラート、または通知を表示するのに最適です。 データは、デフォルトで次の要求のためにのみ持続します。 $リクエスト -

Laravelテストでの簡略化されたHTTP応答のモッキング Laravelテストでの簡略化されたHTTP応答のモッキング Mar 12, 2025 pm 05:09 PM

Laravelは簡潔なHTTP応答シミュレーション構文を提供し、HTTP相互作用テストを簡素化します。このアプローチは、テストシミュレーションをより直感的にしながら、コード冗長性を大幅に削減します。 基本的な実装は、さまざまな応答タイプのショートカットを提供します。 Illuminate \ support \ facades \ httpを使用します。 http :: fake([[ 'google.com' => 'hello world'、 'github.com' => ['foo' => 'bar']、 'forge.laravel.com' =>

LaravelのバックエンドでReactアプリを構築する:パート2、React LaravelのバックエンドでReactアプリを構築する:パート2、React Mar 04, 2025 am 09:33 AM

これは、LaravelバックエンドとのReactアプリケーションの構築に関するシリーズの2番目と最終部分です。シリーズの最初の部分では、基本的な製品上場アプリケーションのためにLaravelを使用してRESTFUL APIを作成しました。このチュートリアルでは、開発者になります

PHPのカール:REST APIでPHPカール拡張機能を使用する方法 PHPのカール:REST APIでPHPカール拡張機能を使用する方法 Mar 14, 2025 am 11:42 AM

PHPクライアントURL(CURL)拡張機能は、開発者にとって強力なツールであり、リモートサーバーやREST APIとのシームレスな対話を可能にします。尊敬されるマルチプロトコルファイル転送ライブラリであるLibcurlを活用することにより、PHP Curlは効率的なexecuを促進します

Codecanyonで12の最高のPHPチャットスクリプト Codecanyonで12の最高のPHPチャットスクリプト Mar 13, 2025 pm 12:08 PM

顧客の最も差し迫った問題にリアルタイムでインスタントソリューションを提供したいですか? ライブチャットを使用すると、顧客とのリアルタイムな会話を行い、すぐに問題を解決できます。それはあなたがあなたのカスタムにより速いサービスを提供することを可能にします

2025 PHP状況調査の発表 2025 PHP状況調査の発表 Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Surveyは、現在のPHP開発動向を調査しています。 開発者や企業に洞察を提供することを目的とした、フレームワークの使用、展開方法、および課題を調査します。 この調査では、現代のPHP Versioの成長が予想されています

See all articles