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) . "'"; } ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access