PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 13 ■ DATABASE PATTERNS


Once again, here is a client perspective on inserting and updating:

$venue = new \woo\domain\Venue();
$venue->setName( "The Likey Lounge-yy" );
// add the object to the database
$mapper->insert( $venue );
// find the object again – just prove it works!
$venue = $mapper->find( $venue->getId() );
print_r( $venue );
// alter our object
$venue->setName( "The Bibble Beer Likey Lounge-yy" );
// call update to enter the amended data
$mapper->update( $venue );
// once again, go back to the database to prove it worked
$venue = $mapper->find( $venue->getId() );
print_r( $venue );


Handling Multiple Rows


The find() method is pretty straightforward, because it only needs to return a single object. What do you
do, though, if you need to pull lots of data from the database? Your first thought may be to return an
array of objects. This will work, but there is a major problem with the approach.
If you return an array, each object in the collection will need to be instantiated first, which, if you
have a result set of 1,000 objects, may be needlessly expensive. An alternative would be to simply return
an array and let the calling code sort out object instantiation. This is possible, but it violates the very
purpose of the Mapper classes.
There is one way you can have your cake and eat it. You can use the built-in Iterator interface.
The Iterator interface requires implementing classes to define methods for querying a list. If you do
this, your class can be used in foreach loops just like an array. There are some people who say that
iterator implementations are unnecessary in a language like PHP with such good support for arrays. Tish
and piffle! I will show you at least three good reasons for using PHP’s built-in Iterator interface in this
chapter.
Table 13–1 shows the methods that the Iterator interface requires.


Table 13–1. Methods Defined by the Iterator Interface


Name Description

rewind() Send pointer to start of list.

current() Return element at current pointer position.

key() Return current key (i.e., pointer value).

next() Return element at current pointer and advance pointer.

valid() Confirm that there is an element at the current pointer position.

In order to implement an Iterator, you need to implement its methods and keep track of your place
within a dataset. How you acquire that data, order it, or otherwise filter it is hidden from the client.

Free download pdf