Page 507 - Beginning PHP 5.3
P. 507
Chapter 15: Making Your Job Easier with PEAR
implode() was explained in Chapter 6, and you can find out more about how regular expressions and
alternatives work in Chapter 18.
Also of note are two uses of the callback rule type. The username field is validated by calling a
checkDuplicateUsername() function (which you get to in a moment); this function returns true if the
chosen username is unique, or false if the username already exists in the database. The emailAddress
field is checked in a similar fashion by using a checkDuplicateEmailAddress() callback function:
$form- > addRule( “username”, “A member with that username already exists in
the database. Please choose another username.”, “callback”,
“checkDuplicateUsername” );
$form- > addRule( “emailAddress”, “A member with that email address already
exists in the database. Please choose another email address, or contact the
webmaster to retrieve your password.”, “callback”,
“checkDuplicateEmailAddress” );
Next come the two callback functions just described. checkDuplicateUsername() expects to be passed
the username to check. It calls Member::getByUsername() to attempt to retrieve an existing member
with the same username. The return value is cast to a Boolean: if a Member object is returned, it is cast to
a value of true , otherwise the resulting value will be false . This value is then negated with the ! (not)
operator to give the correct value for returning from the function:
return !(boolean) Member::getByUsername( $value );
checkDuplicateEmailAddress() works in much the same way, calling Member::
getByEmailAddress() to look for an existing member with the same email address:
return !(boolean) Member::getByEmailAddress( $value );
The processForm() function is a lot simpler than its Chapter 14 counterpart, because all the hard work
of retrieving and validating the submitted form data has already been done by HTML_QuickForm . All
this function does is take an associative array of submitted form field values (passed to it by the HTML_
QuickForm object), add a new password field with the value of the password1 field, and create the
joinDate field based on the current date. This complete array of fields is then passed to the Member
constructor to create the Member object, which is then added to the database by calling its insert()
method:
function processForm( $values ) {
$values[“password”] = $values[“password1”];
$values[“joinDate”] = date( “Y-m-d” );
$member = new Member( $values );
$member- > insert();
}
Thanks to using HTML_QuickForm to do a lot of the heavy lifting (displaying the form, collecting and
validating the submitted data, and reporting errors), this rewritten register.php script is elegant
and easy to read. What ’ s more, it weighs in at just 96 lines of code versus the original script ’ s 127 lines.
Such is the power of reusable code!
469
9/21/09 9:14:57 AM
c15.indd 469
c15.indd 469 9/21/09 9:14:57 AM