The addressBook Class
Now that you have a
Person
, it’s time to turn to the
address book. Just like a physical address book, an
addressBook
object holds a collection of
information about people.
The addressBook
class gives you two actions: you
can either add a new record or search existing records.
That’s it. Updating and deleting records is left for
Version 2.0. However, as always, you want to design the class so that
it’s easy to add these methods.
Like Person
, addressBook
has a
toDOM( )
method, which exports an entire
collection of people to XML as a group.
Constructor
Besides instantiating the object,
addressBook
’s constructor
connects to the database, as shown in Example 10-7.
Example 10-7. addressBook::_ _construct( )
class addressBook implements IteratorAggregate { protected $data; protected $db; public function _ _construct( ) { $this->data = array( ); $this->db = new SQLiteDatabase('addressBook.db'); }
The constructor opens the SQLite database
addressBook.db that was created earlier in Section 10.1. The result handle is stored
in the $db
property.
Adding a Person to an addressBook
An empty address book
isn’t very interesting, so Example 10-8 implements the addPerson( )
method. This method takes a Person
object,
converts it into an SQL query, and inserts it into the database.
Example 10-8. addressBook::addPerson( )
public function addPerson(Person $person) { $data = array( ); foreach ($person as $fields => $value) { $data[$fields] = "'" . sqlite_escape_string($value) . "'"; } ...
Get Upgrading to PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.