As PHP expands to become the server-side program of choice among a significant portion of programmers, professional techniques and programming structures need to be incorporated. Design patterns, a concept borrowed from The Timeless Way of Building by Christopher Alexander (Oxford University Press), refers to a general reusable solution to a commonly occurring problem within a given context. In everyday development work, PHP programmers encounter “commonly occurring problems” in a software development context, and the use of PHP design patterns is a set of solutions to “commonly occurring” PHP programming problems. Pure and simple, PHP design patterns are tools used to deal with the reality of professional software development.
They are not libraries or templates but rather more general structures that can be used to solve problems. I like to think of design patterns in the same way as I do the loop structure. The loop is used when some kind of iteration is required. True, there are other ways to deal with iteration, but a loop is a flexible tool that saves time in the development process. (Besides, it’s a lot neater than writing the same line of code 10,000 times!)
Further, I do not feel constrained by design patterns as “canned
solutions” any more than a loop is a “canned solution” to iteration.
Besides, I can use the loop structure in a variety of ways in PHP ranging
from for
to while
statements and everything in between.
Likewise, design patterns can be implemented in more than one way depending
on the exact nature of the problem being solved.
The most important reason for incorporating design patterns, though, is that they provide solutions to complex problems. As one’s programs become larger, they almost necessarily become more complex. In an object-oriented programming (OOP) environment, such complexity is reduced somewhat, as you are dealing with encapsulated modules, whereas in sequential or procedural programming, any changes can bring the program crashing down like a house of cards. Design patterns bring not only solutions to general programming problems, but they also allow changes to be made in large complex programs by providing loose coupling between objects. So when a change is made, instead of having to start programming all over from scratch, you can just add the necessary changes and everything keeps chugging along—even in large, complex programs.
Further, design patterns are meant for reuse. After all, programmers reuse the same algorithms all the time. Why not use larger structures as well? On the one hand, frameworks and templates serve to make reuse practical, but they are often too specific. That’s where reuse of design-patterned PHP programs comes in, especially in the case of large, complex programs. Because making changes is easy with design patterns, reuse for specific problems of the same kind is easy as well. Reducing developmental time and resources saves money and better serves your clients. They get well-structured programs that do what the clients want, they’re easy for the developers to change (customers always want change!), and they have strong foundations that are not as likely to fail.
At some point, all good programmers realize that they need to get out of a sequential and procedural programming rut. The next logical step is object-oriented programming, and moving into OOP requires a shift in perspective: instead of seeing programming as a series of statements, it must be seen as an interaction and communication between objects. Beyond OOP lie design patterns, where OOP principles are recast into patterns of reusable code. There you will find the tools of professional programmers. Because design patterns for programming were developed in cooperation between academics and businesses, the concepts both transcend single problems while at the same time possessing business-like practicality. Learning PHP design patterns is for professional programmers who want to optimize their own time in development and redevelopment and provide their clients with high-quality code.
In no small measure, this book is for those who felt a certain delight when programming was new to them. This is for the developer who thought nothing of working on a program all night long just because it was interesting, staggering off to bed, only to start on another program as soon as he woke up. When programming is new and every day promises a new discovery or a bug that challenges the developer to a fight to the death, and you must use your mind in complex and exciting ways, the experience can be Zen-like. If you’ve had that experience, you’ll know what I mean. It cannot be spelled out or explained analytically. (I can’t even explain it to myself, and I have no idea why I enjoy the kinds of challenges and rewards found in programming.)
Design patterns reintroduce mental challenges, and this book is not for someone who is new either to PHP or to programming. If you’re learning PHP for the first time, take a look at Robin Nixon’s book, Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition (O’Reilly) before tackling PHP design patterns. Likewise, this book (or any decent book on design patterns) does not promise that you’ll master design patterns quickly and easily. This kind of learning is a journey, and the wisest counsel is to learn to enjoy the journey. It takes time and mental effort.
This book assumes that you know how to program in PHP and want to take your programming skills to the next couple of levels. In fact, it assumes that you’re a pretty good PHP programmer and you’ve used MySQL and know how to develop HTML pages and use CSS. It also assumes that you understand that learning PHP design patterns is not going to happen in a lazy afternoon. Learning design patterns is akin to a gradual metamorphosis.
This book is organized into five parts.
- Part I is an OOP refresher/introduction:
Chapter 1 introduces object-oriented programming (OOP) and how to more easily handle complex programming problems with modularization.
Chapter 2 discusses basic concepts in OOP such as abstraction, encapsulation, inheritance, and polymorphism, as well as the PHP structures that implement these concepts.
Chapter 3 moves on to examine the basic concepts in design patterns, their categorization, and how specific patterns are selected to handle specific problems.
Chapter 4 introduces Unified Modeling Language (UML) and explains how it will be employed in this book.
- Part II covers creational design patterns:
Chapter 5 examines the Factory Method, which has a creational purpose and a class scope. Examples include dynamically creating pages that display graphics, body text, and header text.
Chapter 6 shows how to use the Prototype pattern, which has a creational purpose and an object scope. The Prototype pattern is used when a single object is created as a prototype and then cloned to economically create further instances.
- Part III explains structural design patterns:
Chapter 7 illustrates how to use the Adapter pattern in both class and object scopes. Examples show how to take an existing structure and make changes that allow the developer to add new functionality.
Chapter 8 explains how an existing object can be changed without disrupting a larger program using the Decorator pattern. You’ll see how to decorate male and female dating objects with different preferences in a dating site.
- Part IV looks at behavioral design patterns:
Chapter 9 shows how to use the Template Method pattern—one of the easiest design patterns to both create and use. In addition, you will see how the famous Hollywood Principle operates in design pattern programming. As a final feature of the chapter, two different patterns are combined to solve a single problem.
Chapter 10 presents the State design pattern along with how to use statecharts to map state processes and changes.
- Part V introduces four more behavioral design patterns used in conjunction with MySQL:
Chapter 11 provides the Universal connection class and the Proxy design pattern for adding security to usernames and passwords stored in a MySQL database.
Chapter 12 explains how the Strategy design pattern is significantly different from the State pattern even though they have identical class diagrams. A survey example illustrates how the Strategy pattern can be used with different MySQL requests.
Chapter 13 has multiple examples of how the Chain of Responsibility pattern can be used, ranging from a Help Desk to automatically responding to a date timer to display (in conjunction with the Factory Method pattern) images and text.
Chapter 14 is the first to explore how to use the PHP built-in design pattern interfaces. The Observer design pattern can use interfaces from the Standard PHP Library. Another example uses the Observer design pattern with hand-built interfaces to make a simple content management system (CMS) with PHP and MySQL.
The following typographical conventions are used in this book:
- Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values determined by context.
Tip
This icon signifies a tip, suggestion, or general note.
Caution
This icon indicates a warning or caution.
This book is here to help you get your job done. In general, if this book includes code examples, you may use the code in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Learning PHP Design Patterns by William Sanders (O’Reilly). Copyright 2013 William B. Sanders, 978-1-449-34491-7.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com.
Note
Safari Books Online (www.safaribooksonline.com) is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens more. For more information about Safari Books Online, please visit us online.
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc. |
1005 Gravenstein Highway North |
Sebastopol, CA 95472 |
800-998-9938 (in the United States or Canada) |
707-829-0515 (international or local) |
707-829-0104 (fax) |
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/php_design_patterns.
To comment or ask technical questions about this book, send email to bookquestions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
I want to thank everyone who helped out in one way or another. My colleagues at the University of Hartford’s Multimedia Web Design and Development program were always helpful when I posed a query of one type or another. Professor John Gray, the department chair, was encouraging and helpful as always. Dr. Brian Dorn, my office next-door neighbor, who caught the bulk of my queries, was obliging, knowledgeable, and patient.
I was fortunate enough to meet Michael Bourque of the Boston PHP group at the inaugural Northeast PHP Conference, and appreciate his encouragement for this project. I look forward to working with Michael and the Boston PHP group more in exploring advanced PHP programming.
O’Reilly Media provided three capable technical reviewers. Robin Nixon, author of Learning PHP, MySQL & JavaScript, 2nd Edition (O’Reilly) offered corrections, suggestions, and several insights into PHP to make the code better in many different ways. Aaron Saray, author of Professional PHP Design Patterns (Wrox) was incredibly detailed and generous in his suggestions. He has a wonderful editor’s eye for even the slightest flaw. Aaron and I take very different approaches to design patterns, but such differences provide a wider view for PHP developers interested in design patterns. Finally, Dmitry Sheiko acted as a passionate technical reviewer and has his own blog where his take on PHP design patterns can be found.
Senior Editor Rachel Roumeliotis at O’Reilly Media put all of the many parts together and moved the project along. Maria Gulick, another capable O’Reilly editor, took care of the bits and pieces as the project went through revisions. Copyeditor Jasmine Kwityn found and corrected details I did not know existed—in this galaxy or any other. The whole process was initiated by Margot Maley Hutchison at Waterside Productions, and I am grateful to her as ever.
My wife Delia was more understanding than most spouses since she recently had published a book of her own and knew the process. Our Greater Swiss Mountain Dog, WillDe, could care less about writing processes. As long as he got his treats, he’d go along with anything.
Get Learning PHP Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.