The iterator pattern introduced in the PHP design pattern

Source: Internet
Author: User

Object-oriented programming in a class encapsulates the application logic. Class, which is the instantiated object, each individual object has a specific identity and state. A separate object is a useful way to organize your code, but you typically work with a set of objects or collections.

Property a set of data from a SQL query is a collection, like the list of objects in the Monopoly game example described in the previous section of this book.

The collection is not necessarily homogeneous. Window objects in a graphical user interface frame can collect any number of control objects-Menu, Slider, and Button. Also, a collection can be implemented in a variety of ways: a PHP number is a collection, but it is also a hash table, a list of links, a stack, and a queue.

Problem

How do I manipulate any set of objects?

Solution

Use the iterator pattern to provide unified access to the contents of the collection.

You may not be aware of this, but you use the iterator pattern every day-it lurks in the PHP array type and in various array manipulation functions. (Actually, to give you a combination of arrays of intrinsic classes and a group of variable functions that work with these intrinsic classes, you will have to use these arrays to handle the collection of objects.) This is the local array iteration in PHP:

$test = array(‘one’, ‘two’,  ‘three’);
$output = ‘’; reset($test);
do {
$output .= current($test);
} while (next($test));
echo $output; //  produces ‘onetwothree’

The reset () function moves the iteration back to the beginning of the array, current () returns the value of the present element, and next () advances to the next element in the array and returns the new value (). When you exceed the last element of the array, next () returns false. Using these iterative methods, the internal implementation of the PHP array is irrelevant to you. The iterator combines encapsulation and polymorphism with object-oriented programming principles. With iterators, you can manipulate objects in a collection without having to specifically understand how the collection appears or what the collection contains (the kind of object). Iterators provide a unified interface for different fixed iteration implementations, which completely contain details on how to manipulate specific collections, including which items (filters) and their display order (sort).

Let's create a simple object that operates in an array. (Although the example is in a PHP5 environment, the iterator is not specific to PHP5.) Although more reference operators have been added, most of the examples in this section can be run under PHP4. Object lendable represents media such as movies and photo albums, as part or service of a Web site, allowing users to browse or share their media collections with other users. (For this example, you do not need to consider other aspects.) Let's start with a test of the Lendable Foundation design.

PHP5

class LendableTestCase extends  UnitTestCase {
function TestCheckout() {
$item = new Lendable;
$this- >assertFalse($item->borrower);
$item->checkout(‘John’);
$this->assertEqual(‘borrowed’, $item->status);
$this- >assertEqual(‘John’, $item->borrower);
}
function  TestCheckin() {
$item = new Lendable;
$item->checkout (‘John’);
$item->checkin();
$this->assertEqual (‘library’, $item->status);
$this->assertFalse($item- >borrower);
}
}

To implement the requirements of this initial test, we create a class with several public properties and some methods to trigger the values of these properties:

class Lendable {
public  $status = ‘library’;
public $borrower = ‘’;
public  function checkout($borrower) {
$this->status = ‘borrowed’;
$this->borrower = $borrower;
}
public function checkin() {
$this- >status = ‘library’;
$this->borrower = ‘’;
}
}

Lendable is a good, ordinary beginning. Let's extend it to track items such as DVDs or CDs. The media expands the lendable, and the track details the specific media, including the name of the project, the year of the publication, and the type of the item itself:

class Media extends Lendable {
public $name; public  $type; public $year;
public function __construct($name, $year,  $type=’dvd’ ) {
$this->name = $name;
$this->type =  $type;
$this->year = (int)$year;
}
}

To make things simpler, the media has three common instance variables, Media::name,media::year and Media::type. The constructor takes two parameters, stores the first one in the $name, and the second is stored in the $year. The constructor also allows the optional third parameter to specify the type (the default is DVD).

Given the individual objects to operate, you can now create a container to contain them: the Library. Similar to the common library, the library should be able to add, delete, and compute items in the collection. Even the Library should allow access to a single item (object) in the collection (the Sample Code section of this chapter can see the example).

We started building the Library's test cases.

class LibraryTestCase extends UnitTestCase {
function TestCount()  {
$lib = new Library;
$this->assertEqual(0, $lib->count());
}
}

It is a simple class that satisfies this test:

class Library {
function  count() {
return 0;
}
}

Continue to add some interesting features to the test:

class LibraryTestCase extends UnitTestCase {
function TestCount() {  /* ... */ }
function TestAdd() {
$lib = new Library;
$lib->add (‘one’);
$this->assertEqual(1, $lib->count());
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.