concept contact in category php

appears as: contact, contact, contacts, The contacts, contacts
PHP in Action: Objects, Design, Agility

This is an excerpt from Manning's book PHP in Action: Objects, Design, Agility.

In this chapter, we will be building the internal workings of a contact manager that implements persistence using the MysqlTransaction class from the previous chapter. Working test-first as usual, we will first implement the Contact class and its persistence feature. Then we’ll design and implement a feature that lets us send an email to a contact. To test that, we’ll be using mock objects. Finally, we’ll use a program called fakemail to test the sending of the email for real.

10.1.2. Testing the contact’s persistence

Our contact manager won’t do us much good if the contacts have to be re-entered every time we run it. The contacts have to persist across sessions. That means we have to be able to save a contact to the database and retrieve it again. Where do we start? We write a test, of course:

<?php
require_once('../contact.php');

class TestOfContactPersistence extends UnitTestCase {

    function testContactCanBeFoundAgain() {
        $contact = new Contact('Me', 'me@me.com');
        $transaction = new MysqlTransaction(
                'localhost', 'me', 'secret', 'test');
        $contact->save($transaction);

        $finder = new ContactFinder();
        $contact = $finder->findByName($transaction, 'Me');
        $this->assertEqual($contact->getEmail(), 'me@me.com');
    }
}
?>

The first part of the test saves a new contact to the database. Right now, we assume a Contact object is just a name, an email address, and a save() method. After saving it, we immediately try to retrieve a copy. For finding contacts, we’ll not surprisingly use a ContactFinder class. We’ll take a guess for now, and assume that we will need to find a contact by name. This isn’t unreasonable, but this is not the usual thinking when designing an application. In real life, there would be a requirement driving the code, and we would only add the methods that we definitely need. A complete application would be too much to absorb for an example, so our design is proceeding bottom-up. In the coming chapters, we’ll complete our survey of test driving code, and demonstrate how an application can be built top-down.

Figure 12.6. What the AddContactController does to save the contact to the database