10.5 Assembling the Application

 <  Day Day Up  >  

Finally, you can integrate the classes and templates into a complete application. This section creates a dual web and command-line program that shares the same set of code but abstracts out the details, such as processing the different sources of input data.

10.5.1 Creating the Web Version

The web version gets its input from a form embedded in the HTML template's header, as shown in Example 10-19.

Example 10-19. Web-enabled address book application
 // Configure format-specific details $input = $_POST; $template = new htmlTemplate; // Set mode if (isset($input['mode'])) {     $mode = $input['mode']; } else {     $mode = false; } try {      // Create address book     $ab = new addressBook;     // Load data into Person     $person = new Person($input);          // Add person, if necessary     if ($mode =  = 'add') {         $ab->addPerson($person);     }          // Return results     $ab->search($person);          // Print page     $template->printAll($ab); } catch (Exception $e) {     $ob = ob_start( );     print $e;     error_log(ob_get_clean( )); } 

At the top of Example 10-19, you set a few configuration variables . Since this is the web version, the $input comes from $_POST and the $template is an htmlTemplate . Later, you will set $input and $template to different values in the command-line version.

The $mode variable, which controls whether you should add a new person, is assigned using the mode element of the input source.

Once everything is set up, create the addressBook and Person objects. Use the $input array to configure Person .

Now, if the $mode is set to add , call addPerson( ) to insert the person into the database. This converts Person into SQL and makes a new entry.

The next step is populating the address book with results. If you're doing a search, $ab contains all the matching records. If you're inserting a record, $ab contains the new record.

The last action is the call to print out your template methods using the handy printAll( ) method instead of making individual calls.

All that assumes, of course, that everything goes smoothly and you encounter no exceptions. Many of the underlying methods throw exceptions, some because the extension does so automatically and some because you're actually throw ing them yourself.

However, here's where the benefit of exceptions shines through. You don't need to worry which methods do or don't throw exceptions, nor do you need to care if the exception is actually thrown by a second method called by a first one. Everything propagates up to this location and is caught by your catch block. You've effectively replaced the necessity to check the return value of every function and method in your application with five lines:

 } catch (Exception $e) {     $ob = ob_start( );     print $e;     error_log(ob_get_clean( )); } 

As described in Chapter 7, you can print an exception to get a full set of debugging messages. By wrapping the print call within a output buffer, you can redirect these lines from the screen to the error log.

For example, when the SQLite can't find the person database table, you get:

  [Thu Jul 22 10:30:14 2004] [error] exception 'SQLiteException' with message   'SQL logic error or missing database' in   /www/www.example.com/addressBook/index.php:48   Stack trace:   #0 /www/www.example.com/addressBook/index.php(48): addressBook->search(Object(Person))   #1 {main}  

Sure, you still need to check occasional return values at the component level, i.e., inside individual methods. However, those checks are all encapsulated within your objects, so they occur at a lower level. When you assemble a program by combining multiple objects together, which is a higher level of programming, you only need to handle exceptions.

One thing your code doesn't do is print out any error message to a person using the address book. This is discussed later on in this chapter, in Section 10.6.

10.5.2 Creating the Command-Line Version

The largest difference between the command-line version and the web version is that you need to parse command-line options yourself. The easiest way to do this is with PEAR's Console_Getopt class, as shown in Example 10-20.

Example 10-20. Command-line-enabled address book application
 require_once('Console/Getopt.php'); $opts = new Console_Getopt; // Accept these four optional command line flags. $longopts  = array('mode=', 'firstname=', 'lastname=', 'email='); $parsed = $opts->getopt($argv, NULL, $longopts); // Strip leading "--" from flag name // Convert from getopt( ) array return format to one like $_POST foreach ($parsed[0] as $opt) {     $key = substr($opt[0], 2);     $input[$key] = $opt[1]; } $template = new textTemplate; 

Console_Getopt parses $argv and breaks it apart into option pairs. You specify any or all of four possible options: --mode , --firstname , --lastname , and --email .

Since getopt( ) doesn't return an array that's formatted like $_REQUEST , you need to rework the array it returns. This requires you to strip the leading -- from the option name and reorganize how the information is stored.

After fixing $input , set the $template to new textTemplate .

And now you're done. There's nothing left to modify in the program. This command runs the command-line version of the address book program, ab.php , and searches for people with a first name of Rasmus :

 $ php ab.php --firstname=Rasmus  -------------------------------------------------------------------   Rasmus Lerdorf  rasmus@php.net   -------------------------------------------------------------------  

Passing --firstname=Rasmus on the command line is equivalent to setting the form element firstname to Rasmus .

10.5.3 Creating a Unified Program

The final step is unifying the two versions into a single program. This requires you to differentiate between the command-line and web versions of PHP.

The function php_sapi_name( ) checks which version of PHP you're running and returns its name. When you're running under the command-line version, it returns cli . The unified application code shown in Example 10-21.

Example 10-21. Unified address book application
 // Configure format-specific details if (php_sapi_name( ) =  = 'cli') {     require_once('Console/Getopt.php');     $opts = new Console_Getopt;     $longopts  = array('mode=', 'firstname=', 'lastname=', 'email=');     $parsed = $opts->getopt($argv, NULL, $longopts);     foreach($parsed[0] as $opt) {         $key = substr($opt[0], 2);         $input[$key] = $opt[1];     }     $template = new textTemplate; } else {     $input = $_REQUEST;     $template = new htmlTemplate; } // Set mode if (isset($input['mode'])) {     $mode = $input['mode']; } else {     $mode = false; } try {     // Create address book     $ab = new addressBook;     // Load data into Person     $person = new Person($input);          if ($mode =  = 'add') {         $ab->addPerson($person);     }          // Return results     $ab->search($person);          $template->printAll($ab); } catch (Exception $e) {     $ob = ob_start( );     print $e;     error_log(ob_get_clean( )); } 

Now the program will parse $argv and print text when it's run from the command line, but also produce HTML when executed under a web server.

 <  Day Day Up  >  


Upgrading to PHP 5
Upgrading to PHP 5
ISBN: 0596006365
EAN: 2147483647
Year: 2004
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net