Lendable is a good, generic start. Let's extend it to track items like DVDs or CDs. Media extends Lendable and tracks details about specific media, including the name of the item, the year it was released, and what type of item it is: class Media extends Lendable { To keep things simple, Media has three public instance variables, Media::name, Media::year, and Media::type. The constructor takes two arguments and stores the first in $name and the second in $year. The constructor also allows an optional third parameter to specify type (which defaults to "dvd"). Given individual objects to manipulate, you can now create a container to hold them: a Library. Like a regular library, Library should be able to add, remove and count the items in the collection. Eventually, Library should also permit access to individual items (objects) in the collection (which is shown momentarily in the Sample Code section of this chapter). For right now, let's build a test case for Library. class LibraryTestCase extends UnitTestCase { It's easy enough to write a class that satisfies this test: class Library { Let's continue and add some interesting features to the test: class LibraryTestCase extends UnitTestCase { An easy way to implement add() is to piggyback on PHP's flexible array functions: you can add items to an array instance variable and use count() to return the number of items in the collection. class Library { Library is now a collection, but it provides no way to retrieve or manipulate the individual members of the collection. Let's move on to the purpose of the chapter, implementation of the Iterator design pattern. The following UML class diagram shows the GoF Iterator pattern with the Media and Library classes used to make the example concrete.
In the Sample Code section, the LibraryGofIterator class is an example of a direct implementation of the GoF Iterator design pattern.
blog comments powered by Disqus |