Preface

This book aspires to replace trust in commercial products with reliance on open-source software and your own ingenuity.

We’ve all been in a situation in which a customer wants to solve some complicated information-services problem without spending much money. Maybe the project is a one-off demonstration that’s unlikely to lead to much of a sale. Maybe it’s a proof-of-concept project that may never get real funding. Maybe, and this isn’t uncommon at all, the customer is just cheap and wants a real, highly capable, production solution for the absolute least amount of money possible. The application typically is feature rich, with a substantial data model backing it up. It may be something like a travel reservation system, a catalog, a data warehouse full of scientific of business data, or, as is modeled in several chapters of this book, an accounting system.

These are the sorts of applications for which Microsoft touts the .NET Framework and Sun Microsystems sells Enterprise Java. Those are extraordinarily capable development environments. They are also more or less proprietary, and dependent on expensive software licenses.

The environment that seems to be emerging in many companies is one in which the first budget line item to fall is the one for software licenses. That means open-source software fits the budget, and often its capabilities stack up quite favorably against its commercially licensed competitors. But if the motto of the open-source community is “do it yourself,” there’s bound to be some professional services time required to make the software do what’s needed.

Multi-Tier Application Programming with PHP: Practical Guide for Architects and Programmers is meant for people who find themselves—or would like to find themselves—in the position of having to provide those professional services.

Goals and Audience of this Book

The aim of this book is to show you how to solve complicated information-systems problems with little more than software you can download freely from the Web, namely PHP and an open-source database server, such as MySQL or PostgreSQL. To solve such complicated problems, you’ll want to use multi-tier application architecture, specifically a strategy called the model-view-controller (MVC) pattern.

Goals

Before you start designing applications, you’ll need to understand what multi-tier design is all about, and how to implement it with PHP and related technologies. You’ll also need some design guidance as to when it’s appropriate to try to structure your applications as multi-tier entities under PHP, when it’s better to go for a full-blown solution under an application server (as with Enterprise Java), and when a more traditional PHP solution is best.

The essence of multi-tier (usually, it boils down to three-tier) application design is the separation of the logical functions of an application into several layers:

image The accessor layer (the model) manages interaction with a database management system (DBMS). Its job is to query the database as efficiently as possible, making optimum use of the available database connections and sharing database access across multiple lower-level activities where possible. It exposes methods that represent abstractions of what’s in the database.

image The business-logic layer (the controller) decides what sort of data to extract from the database under various conditions. Further, it can process that data to yield meaningful information. For example, the business-logic layer might be set up to request revenue and expenditure data from the persistence layer, then process those pieces of information and expose a method that returns a profit figure.

image The presentation layer (the view) is concerned with providing an interface to the user. It presents a user interface (in hypertext markup language [HTML], typically) that the user can manipulate, and it formats the results of the business-logic layer’s work in an attractive way.

The advantage of designing applications this way is ease of maintenance and modification, as well as better performance under load.

PHP has met tremendous success in the space between static Web pages (simple, not very flexible, and hard to maintain) and three- or four-tier enterprise applications under an application server like WebSphere or WebLogic (which are hard to learn, complicated, expensive, and not worth the trouble for any but the largest projects). For the bulk of network applications—which require database connectivity, interaction with a user via forms, an ability to output HTML, and some mechanism for maintaining state in the inherently stateless environment of hypertext transport protocol (HTTP)—PHP and MySQL do everything required. Solutions built around these technologies are fun to design, easy to create, low in cost, and equal or greater in performance to similar applications written with the Microsoft .NET Framework or Enterprise Java.

The subject of this book is taking PHP a step further by separating the presentation layer from the business-logic layer. The book aims to teach programmers how to do this, and why such a layered design is superior to more traditional approaches in many situations.

Readers should come away from Multi-Tier Application Programming with PHP: Practical Guide for Architects and Programmers different in several ways:

image They should be familiar with the principles of multi-tier software architecture.

image They should be more skilled with the PHP language, and particularly with those elements that are part of PEAR DB or new in PHP 5.

image They should tend to think about PHP in association with large software projects for which they might have discounted it before.

This book does not aspire to teach you PHP. Lots of excellent tutorial and reference books exist, and there’s a great deal of PHP educational material online. This book shows how PHP can be used in a new way—as a tool for creating multi-tier frameworks into which useful applications can be built. You can enjoy the benefits of multi-tier software design under PHP with a much smaller investment in learning than would be required by other languages.

This book deals with programming—actual code samples and commentaries on them—primarily in the areas that are unique to multi-tier design. A chapter deals with object orientation in PHP as it applies to the architecture, whereas other chapters have to do with HTTP and simple object access protocol (SOAP), the two communication protocols most useful in tying together multiple layers. There’s also coverage of database design and query construction, and some information about tricks you can use in generating user interfaces.

Audience

The intended audience of Multi-Tier Application Programming with PHP: Practical Guide for Architects and Programmers includes people with an interest in PHP beyond its applications as a quick and cheap way to solve server-side programming problems in the course of building Web sites. They’re not so much interested in PHP as an alternative to ASP and Perl, but in PHP as a language that can deliver excellent results when placed in direct competition with Microsoft .NET and Enterprise Java.

The people who will appreciate this book most are those who have a working knowledge of HTML and JavaScript, and familiarity with at least one full-fledged programming language, such as C, Java, or Visual Basic. They probably also will know how to program in PHP, ASP, or Perl for the purpose of doing server-side scripting work, including how to connect to and use database servers (possibly under the relatively new PEAR DB system). For that reason, they’ll know the essentials of structured query language (SQL) as well.

The people who read and learn from this book will be able do something (implement a multi-tier architecture) for nearly nothing (PHP is free, many of its associated database servers are free or nearly so, and PHP is a lot easier to learn than Microsoft .NET and Enterprise Java).

The Road Ahead

Here’s a quick introduction to the structure of this book, chapter by chapter.

1. Introduction. This chapter explains the theory of multi-tier design and why you’d want to use one. It also gets into the question of when you’d want to consider PHP and an open-source database server for implementing a multi-tier design, and when a commercial solution might prove superior.

2. Principles of Object Orientation in PHP. This chapter shows you how PHP, particularly its newer versions, implement the principles of object orientation.

3. HTTP in PHP. Key to any online application is HTTP. PHP has a particular way of interacting with HTTP, and this chapter explains it to you.

4. SOAP under PHP. As you’ll see in Chapter 4, SOAP is a very flexible way of communicating between tiers, even if there’s a firewall or other security mechanism in the way (that’s because SOAP rides on top of HTTP or simple mail transport protocol [SMTP], two protocols to which that firewalls usually allow free passage). Techniques for implementing SOAP with the NuSOAP libraries are explained in this chapter.

5. Designing and Implementing a Multi-Tier Application in PHP: A Succinct Example. This chapter deals with design principles, including the question of how to establish communications among layers if everything is separated by a network. You’ll find a complete multi-tier application (a simple Great Circle navigation calculator) described here, enabling you to work through a full project with relative speed.

6. The Persistence Layer. In Chapter 6, we begin the elaborate example that concerns us throughout much of this book: Currawong Accounting. Named for an Australian bird, Currawong Accounting is a multicurrency bookkeeping application. In this chapter, we design a data model (a database schema) for Currawong and implement it in MySQL, using the dependency features of InnoDB tables.

7. The Accessor Layer. With our database in place, we set about writing the PHP programs that execute SQL queries. This chapter is very much concerned with the PEAR DB way of interfacing with a database, as well as with establishing SOAP servers with the help of the NuSOAP library.

8. Business Logic. The logic layer is where calculations take place, and in Currawong Accounting it’s where we do our report creation. Further, the logic layer in Currawong is interesting because it receives HTTP POST input and makes request of the accessor layer as a SOAP client.

9. The Presentation Layer. Concerned with providing an interface (a human interface in the form of Web pages, in the Currawong case), the presentation layer involves HTML markup. It also involves HTML forms, some direct calls the accessor layer for the purpose of showing database table contents, and interactions with the logic layer.

10. The Elsewhere Layer. Because Currawong Accounting is meant to run on a Web server, it will have access to all sorts of resources on the public Internet. Among these: Web services that give information on currency exchange rates. The elsewhere layer of Currawong Accounting queries one of these services in order to discover the relative values of the currencies the application tracks.

Setting Up Your Development Environment

In learning any programming language or design strategy, it’s vitally important that you actually do the work—go hands on with the code and try to solve some problems. The main point of doing this is not so much the solving of the problems as the making of mistakes, because it is through mistakes that we learn. Software work, in which little things like the sequence of arguments or the placement of a brace can have far-reaching effects, is particularly well suited to mistake making.

The key thing is to be able to figure out your mistakes quickly, learn from them, and move on to the next thing. Battering away at one problem, for hours because you’re SURE you’ve done everything right and it JUST WON’T WORK, ranks among life’s most frustrating experiences. It’s particularly unamusing when the error turns out to be trivial.

Similarly not fun is troubleshooting your infrastructure. The programs in this book make use of the very reliable and field-proven PHP interpreter and the MySQL database engine, but those pieces of software, in and of themselves, are not why you should be reading this book. It’s what you can do with them that we’re interested in here. So get them installed right and don’t worry about them.

The point: Get your working environment built right and get on with the learning. Then, you’ll be ready to get on with the production coding, as well. Your development environment is your factory production floor. The rest of this section offers some tips on doing so.

On the Arrangement of Machines

The whole point of multi-tier software architecture is the possibility of separating software components so they run on different machines, thus improving reliability, scalability, and, under some conditions, performance (you’ll read all about the advantages and disadvantages of multi-tier design in Chapter 1). In a development environment, however, it’s not as critical that you distribute pieces of your applications across multiple machines. That’s because the advantages of distributing the tiers become most evident when the application is experiencing heavy load—in other words, in production.

On the other hand, it’s nice to be able to carry your entire development project around on a single notebook computer. One possible solution to the problem of network simulation involves virtual machines. VMWare (http://www.vmware.com) makes a number of products that allow you to run multiple virtual machines within your “real” operating system (VMWare Workstation is the simplest of the lot, and fits the purposes of this book). The software is pretty clever; it walls off a section of your machine’s memory and hard disk and allows you to treat those protected resources as a separate machine. You have to install an operating system (which may or may not be the same as your “host” operating system) on the protected area and everything. VMWare manages the work of sharing the CPU among your host system and your virtual machines (you need a lot of RAM if you want to have more than one virtual machine running at once, though). The machines share the network card, too, so both can get separate DHCP addresses from the same router and communicate with each other over the local area network (LAN).

Server Software

Programs written in PHP will run on any machine for which there is a PHP interpreter. At the moment, compiled interpreters exist for about 10 operating systems, including IBM OS/2 and AmigaOS, and you can port the freely downloadable source code to a new one if you want. Regardless, the chief PHP environments are Microsoft Windows and the various kinds of Linux, and those are the ones we focus on here.

Linux

You’ll want to configure a Linux system as a LAMP server (Linux, Apache, MySQL, PHP) for the purposes of this book. In other words, you’ll want to install these pieces of software:

image Linux (http://www.linux.org). Choose your favorite distribution. Anything based on the 2.4.x kernel will certainly work, as will significantly older versions.

image Apache (http://www.apache.org). Install the Apache HTTP server on top of Linux. The easiest way to do this is by installing the package that fits your Linux distribution (an RPM file for Red Hat Linux, for example), but you can compile the source if you prefer.

image MySQL (http://www.mysql.com). Next comes the MySQL database server. Again, use your distribution’s package-management solution if you can, or build it yourself.

image PHP (http://www.php.net). Install PHP last. You can compile the source, or install the package that fits your distribution.

Microsoft Windows

Under Microsoft Windows, you have a choice of two major Web servers:

image Microsoft Internet Information Services (IIS). Windows’ native HTTP server, IIS can be installed from the Windows distribution CD-ROM.

image Apache (http://www.apache.org). Download and install the Microsoft Windows binary files.

Once you have an HTTP server in place, you can install the rest of the critical server software:

image MySQL (http://www.mysql.com). You’ll want to download the Windows binary from the MySQL site. It installs automatically, with practically no decisions for you to make.

image PHP (http://www.php.net). As with Linux, install the PHP binary last. If you chose the IIS Web server, configuration is automatic. If you opted for Apache under Windows, you have to do some manual configuration that’s documented in a file that comes with the PHP binary kit.

The Client Side

My client computer is a notebook running Microsoft Windows 2000 (it happens to the be the Server variety of Windows 2000, but that’s not because of anything related to PHP). I sincerely would like to use Linux outside of the server environment (read about the new file system rumored to be part of Longhorn—that’s project name for the next version of Microsoft Windows—and you’ll see why), but I have not yet made the leap with my working notebook.

On the client side, you’ll be doing two things most of the time: writing code and testing it.

Writing code in PHP, HTML, JavaScript, and SQL—the four languages you’ll use in following this book—is best handled by your text editor of choice, which for me is a product called NoteTab Pro from a company called Fookes Software. Read all about it, and download a trial version, from http://www.notetab.com. I write all my code and prose—every last word of this book, as a matter of fact—in NoteTab Pro. It has a tabbed interface with which you can have many documents open at once, its search-and-replace function supports regular expressions, and its macro language is intelligent. Writing in plain text removes formatting surprises from my life, and formatting surprises are surprises I don’t need. About the only thing I really wish NoteTab had is syntax highlighting for various programming languages, mainly PHP. Editor wars being what they are, though, I will leave my discussion of the subject at that.

To test your PHP programs, you’ll need a Web browser. It’s true that not all PHP programs are meant to be rendered in browser-interpretable markup languages, and in fact the accessor- and logic-layer programs described in this book do not generate HTML output. To test these, though, we’ll use a special HTML document that makes the required calls and displays debugging output, all within a browser window (you’ll see how to create that tester later). In writing this book, I did my development and testing with Microsoft Internet Explorer 6.0. You can get your own copy of that browser from http://www.microsoft.com/windows/ie. The HTML and JavaScript in these pages aren’t too fancy, though, and should work well in any semimodern Web browser.

You’ll want to do testing of your SQL statements independent of PHP and HTML. That means you’ll need a client for whatever database server you choose to use. If you’re going to use MySQL—and that’s what appears in this book’s examples—you’ll very likely be happy with MySQL Control Center. It’s available at http://www.mysql.com/products/mysqlcc. Its capabilities are covered more fully in Chapters 6 and 7.

Other software tools I keep in my PHP programming toolkit include:

image Effetech HTTP Sniffer (http://www.effetech.com). A monitoring program that keeps track of HTTP calls among network nodes. When all else fails, you can use this to make absolutely sure that your Web services are returning the results you are expecting them to return.

image Search and Replace Funduc Software (http://www.funduc.com/srshareware.htm). A simple, elegant program that will look through many files to find (and, if you like, replace) a specified string or regular expression. It’s handy for work like changing a machine name or IP address globally.

image CASE Studio (http://www.casestudio.com). A database entity modeler (schema-generation tool), CASE studio will connect to a database server (any of several kinds, including all the popular open-source ones) and figure out the table relationships in a specified existing database.

I have not outfitted my development environment with any of the Zend Studio software (http://www.zend.com) yet, mainly because I haven’t felt like giving up the money (the version of Zend Studio with the handiest features costs $195, U.S. dollars). I’ve worked a bit with their time-limited demo version, though, and I think it’s great. The ability to step through programs as they execute is extraordinarily useful, and the environment’s variable-monitoring capability eliminates the need to insert thousands of echo statements during debugging work. Code completion and the on-screen function reference speed development, too. I’ll probably go to Zend Studio before long.

Shortcut: Setting Up the Example Applications

Setting up the example applications is easy. Essentially, once you have the proper server infrastructure set up, you can just copy the application directories into the server’s Web root and begin using them right away. Here’s a step-by-step procedure, assuming you have nothing but a Linux or Microsoft Windows server to begin. This section is designed to help you get the example applications up and running quickly; there is some overlap with the more deliberate steps described in the preceding section.

1. Install and test the Web server of your choice. Apache Web Server (http://www.apache.org) is the best option for Linux, whereas both Apache and Microsoft Internet Information Services are good alternatives for Windows. Use Apache 1.3.x or 2.0.x—either branch of the Apache product line is acceptable.

2. Install and test MySQL (http://www.mysql.com) for your machine. It’s important that you use MySQL 4.0.1x, or a newer version, because it’s only in these that the InnoDB table type (used to provide enforced relationships among tables) is available. If you want to use a database other than MySQL, you’ll have to edit the code in the accessor layer—a small but important task—to modify the way in which the programs connect to the database.

3. Install and test PHP (http://www.php.net) for your machine, making sure that it interprets a simple “Hello, World” script as expected. Use PHP version 4.3.x or newer. PHP 5.x is acceptable.

4. Locate the Web root directory on your machine. On an Apache server, it’s usually called htdocs; on an IIS machine, it’s usually called wwwroot.

5. Into that folder, copy the entire contents (including subdirectories) of the acct and greatCircle directories that you downloaded from the book’s support site.

6. Copy the contents of the Required Libraries folder—graph, nusoap-0.6, and PEARDB—into a directory that’s specified in the include_path line of your server’s php.ini file. Usually, one of these is /php/includes.

7. Before the applications will work properly, you’ll have to run their database-preparation scripts.

image For the Great Circle navigation program, run cities.sql and citiesPopulator.sql, in that order.

image For Currawong Accounting, run /DBSetup/currawongTables.sql and /DBSetup/populator.sql, in that order.

You should then be able to run the Great Circle program by navigating to this URL: http://<servername>/greatCircIe/calcGreatCircle.php. You should be able to run Currawong Accounting by opening this URL: http://<servername>/acct/app.html.

Other Resources

Most of the nonsoftware resources you’ll use in your PHP development work have to do with information. PHP isn’t quite as vast as, say, Java, but it’s not trivial, and you will almost certainly want to refer to a reference often. References take the form of Web sites, books, discussion groups, and—heaven forfend!—human beings.

Books

Books most definitely have a place on the desks of the software architect and programmer. Very often, it’s easier to go to a book for an answer than to a reference site, even for quick-reference questions. Books really come in handy when the question is more complicated than, “What are the keys in the associative array returned by the localtime() function?” Very often, authors have solved problems like yours and have published their strategies. The books that I referred to most often during this project were:

image Programming PHP by Rasmus Lerdorf and Kevin Tatroe (Sebastopol, CA, O’Reilly, 2002). The standard text for getting things done in PHP 4.1, it’s the one I turn to when I’ve been working with some other language and need information about how the standard problems are solved in PHP.

image MySQL Cookbook by Paul DuBois (Sebastopol, CA, O’Reilly, 2003). More than a reference for MySQL, this book shows you how to solve problems—it’s extraordinarily practical.

image Web Database Applications with PHP & MySQL by Hugh Williams and David Lane (Sebastopol, CA, O’Reilly, 2002). A fair collection of PHP solutions to elaborate problems.

image JavaScript Bible by Danny Goodman (IDG Books, Boston, 1998). A combination tutorial/reference to JavaScript (and the tricky parts of HTML, as well), this book has the right combination of solutions to problems and straight object-reference material. Full disclosure: I did some of the technical editing work on this book.

image Linux: Rute User’s Tutorial and Exposition by Paul Sheer (Prentice Hall PTR, 2002). An excellent guide to the Linux operating system, well suited to someone who wants to configure a server to run reliably in the background.

image Database Design for Mere Mortals by Michael Hernandez (Addison-Wesley, 2003). Database design is a really specialized field, but Hernandez does a good job of teaching it. Because getting your database design right is the greater part of getting your multi-tier application right, it pays to learn design well.

Web Sites

The Internet makes heaps of information available easily and quickly, and usually free of charge in the case of PHP and its related technologies. Here are some of the sites you’ll find handy as you do development work:

image PHP.net (http://www.php.net). The authoritative PHP site contains the official documentation, and lots of user comments that will usually help you solve your own problems.

image MySQL.com (http://www.mysql.com). The official MySQL site includes complete documentation of the MySQL variant of the SQL language, as well as links to many MySQL utilities.

image Sourceforge (http://www.sourceforge.net). Have a look here for software projects in progress, PHP-related or otherwise. Because source code is always available (and licensing usually liberal), you can often adapt resources here to fit your needs.

image PHPBuilder (http://www.phpbuilder.net). Another code library site, this one PHP specific, PHPBuilder often will show you how someone else has already solved your problem, or one similar.

image Safari (http://safari.oreilly.com). This commercial site (which offers a free two-week demo) enables you to access the full text of hundreds of technical books from several big publishers. It’s a great place to look for recipes, code snippets, and quick answers, but it is designed to make reading or printing long passages inconvenient (that’s how they sell paper books).

Discussion Groups

Discussion groups, facilitated by the Internet, are a great way to get answers to development-related questions. It can take some time to phrase your question in a useful way, and you’ll run into smartypants replies more often that would be ideal, but generally these groups are great resources:

image comp.lang.php

image php.general

image php.db

image Various mailing lists (http://www.php.net/mailing-lists.php)

Human Beings

There’s a significant PHP community developing, and lots of people—training companies, consultancies, product vendors, and others—have an interest in encouraging its growth. As a result, you’ll find it fairly easy to find a PHP event to attend. The PHP home page (http://www.php.net) includes a calendar of events, which in turn links to the pages of local PHP users groups that host activities. Most major cities have at least one PHP get-together at a local bar or restaurant every month.

Good luck implementing multi-tier architectures under PHP. Please share your experiences with me, as well as your comments on this book and your ideas for future editions. Visit my Web site at http://www.davidwall.com, and reach me by electronic mail at [email protected].

Acknowledgments

A book, particularly a technical one, is a collaborative effort. Not only does an author have to consult with other people in his effort to fill the gaps in his knowledge, he must build atop the tangible prior efforts of others. This is particularly true when the author is working with open-source software, which derives from a community. I have benefited from the assistance, direct and indirect, of dozens of people in the course of writing this book.

Thanks to Karyn Johnson and the rest of the editorial team at Morgan Kaufmann. I would also like to thank the project manager, Kristin Macek, the design manager, Cate Barr, and the production editor, Dan Fitzgerald. They all work hard to deliver quality books.

Thanks to James Connor, Matt Wade, Guillermo Francia, and Peter Gale, who reviewed the code and text and contributed a great deal to them. Their comments were invaluable.

Thanks to Herman Veluwenkamp, whose spectacular Graph class features prominently in Chapter 8.

Kudos to the PHP community, which delivers better software and far better support than most commercial enterprises.

Thanks to Bruce and Connie Wilkinson, Adam and Nikki Bergman, Philippe and Lydie Vacher, Greg and Wen Smith, Bryan and Suzanne Pfaffenberger, Derek and Gwen Tom, Jacqueline Vacher, Gary Chin, Geoff May, Diana Yap, Ken Lau, Nicole Pritchard, Daniel Sjuc, Jo Wong, Paul Comrie-Thomson, Alessandro Lima, and Jairson Vitorino. They are friends and colleagues I am lucky to know.

Thanks to my family as always.

David Wall

Paris

January 2004

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.141.202