PHP Advanced and Object-Oriented Programming
Total Page:16
File Type:pdf, Size:1020Kb
VISUAL QUICKPRO GUIDE PHP Advanced and Object-Oriented Programming LARRY ULLMAN Peachpit Press Visual QuickPro Guide PHP Advanced and Object-Oriented Programming Larry Ullman Peachpit Press 1249 Eighth Street Berkeley, CA 94710 Find us on the Web at: www.peachpit.com To report errors, please send a note to: [email protected] Peachpit Press is a division of Pearson Education. Copyright © 2013 by Larry Ullman Acquisitions Editor: Rebecca Gulick Production Coordinator: Myrna Vladic Copy Editor: Liz Welch Technical Reviewer: Alan Solis Compositor: Danielle Foster Proofreader: Patricia Pane Indexer: Valerie Haynes Perry Cover Design: RHDG / Riezebos Holzbaur Design Group, Peachpit Press Interior Design: Peachpit Press Logo Design: MINE™ www.minesf.com Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected]. Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit Press shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it. Trademarks Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson Education. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. 13-digit ISBN: 978-0-321-83218-4 10-digit ISBN: 0-321-83218-3 9 8 7 6 5 4 3 2 1 Printed and bound in the United States of America Dedication To my good friend Michael K. and his family: I cannot thank you all enough for your continuing friendship, generosity, and kindness over these many years. My utmost thanks to… Jessica, the love of my life, for just about everything. Zoe and Sam, for making my world a better place. Everyone at Peachpit Press for their support, for their dedication to putting out quality books, and for everything else they do to make all this happen. The most excellent editor, Rebecca Gulick, for so many reasons. Liz Welch, for her spot-on copyediting and attention to detail. The production coordinator, Myrna Vladic, the compositor, Danielle Foster, the proofreader, Patricia Pane, and the indexer, Valerie Haynes Perry, who turn my mess of files into an actual book. Alan Solis, for his very, very helpful technical review. Thomas Larsson, for his input on the design patterns chapter. Always helpful to get even one more extra set of eyes! Tjobbe Andrews (h t t p://t a w d.c o.u k ), for volunteering to create a new HTML5 design for the example chapter. And for doing so on such short notice! Sara, for entertaining the kids so that I can get some work done, even if I’d rather not. The readers, the readers, the readers! Table of Contents Introduction . ix Chapter 1 Advanced PHP Techniques . 1 Multidimensional Arrays . 2 Advanced Function Definitions . 17 The Heredoc Syntax . 31 Using printf() and sprintf(). 37 Review and Pursue . 42 Chapter 2 Developing Web Applications . 43 Modularizing a Web Site . 44 Improved SEO with mod_rewrite . 67 Affecting the Browser Cache . 75 Review and Pursue . 80 Chapter 3 Advanced Database Concepts . 81 Storing Sessions in a Database . 82 Working with U.S. Zip Codes . 96 Creating Stored Functions . 108 Displaying Results Horizontally . 112 Review and Pursue . 118 Chapter 4 Basic Object-Oriented Programming . 119 OOP Theory . .120 Defining a Class . 121 Creating an Object . 124 The $this Attribute . 127 Creating Constructors . 133 Creating Destructors . 136 Designing Classes with UML . .140 Better Documentation with phpDocumentor. .143 Review and Pursue . 148 Table of Contents v Chapter 5 Advanced OOP . 149 Advanced Theories . 150 Inheriting Classes . .152 Inheriting Constructors and Destructors . 157 Overriding Methods. .161 Access Control. .165 Using the Scope Resolution Operator . 172 Creating Static Members . 176 Review and Pursue . .182 Chapter 6 More Advanced OOP . 183 Abstract Classes and Methods . .184 Interfaces. .191 Traits . 197 Type Hinting . 203 Namespaces . 207 Review and Pursue . 212 Chapter 7 Design Patterns . 213 Understanding Design Patterns . 214 The Singleton Pattern. 216 The Factory Pattern . 220 The Composite Pattern . 225 The Strategy Pattern . 233 Review and Pursue . 242 Chapter 8 Using Existing Classes . 243 Catching Exceptions . 244 Extending the Exception Class. 251 Using PDO . 258 Using the Standard PHP Library . 270 Review and Pursue . 282 Chapter 9 Example—CMS with OOP . 283 Identifying the Goals . 284 Creating the Database . 286 Making the Template . 290 Writing a Utilities File . 294 Creating the Error View File . 297 vi Table of Contents Defining the Classes . 299 Creating the Home Page . .304 Viewing a Page . 308 Using HTML_QuickForm2 . 312 Logging Out . 320 Adding Pages . 322 Review and Pursue . 326 Chapter 10 Networking with PHP . 327 Accessing Other Web Sites . 328 Working with Sockets . 333 Performing IP Geolocation . 339 Using cURL . 343 Creating Web Services . 347 Review and Pursue . 352 Chapter 11 PHP and the Server . .353 Compressing Files. 354 Establishing a cron . 363 Using MCrypt . 366 Review and Pursue . 376 Chapter 12 PHP’s Command-Line Interface . .377 Testing Your Installation . 378 Executing Bits of Code . 383 Interactive PHP CLI . .386 Creating a Command-Line Script . 388 Running a Command-Line Script . 391 Working with Command-Line Arguments . 395 Taking Input . 400 Built-In Server . .405 Review and Pursue . 408 Chapter 13 XML and PHP . .409 What Is XML?. 410 XML Syntax. 412 Attributes, Empty Elements, and Entities . 415 Defining XML Schemas . 419 Parsing XML . 432 Table of Contents vii Creating an RSS Feed. 447 Review and Pursue . 452 Chapter 14 Debugging, Testing, and Performance . 453 Debugging Tools . 454 Unit Testing . 460 Profiling Scripts . 471 Improving Performance. 473 Review and Pursue . 476 Index . 477 viii Table of Contents Introduction In this humble author’s (or not-so-humble About This Book author’s) opinion, “advanced PHP” is about continuing to learn: you already know how Simply put, I’ve tried to make this book’s to use PHP, and presumably MySQL, for content accessible and useful for every all the standard stuff, and now it’s time to PHP intermediate-level programmer out expand that knowledge. This new knowl- there. As I suggest in the introductory edge can range from how to do different paragraphs, I believe that “advanced” PHP things, how to improve on the basic things, is mostly a matter of extended topics. You and how other technologies intersect with already possess all the basic knowledge— PHP. In short, you know how to make a you retrieve database query results in your dynamic Web site with PHP, but you’d like sleep—but want to go further. This may to know how to make a better Web site, mean learning object-oriented program- with every possible meaning of “better.” ming (OOP), using PEAR (PHP Extension and Application Repository), invoking PHP This is the approach I’ve taken in writing on the command line, picking up eXtensi- this book. I haven’t set out to blow your ble Markup Language (XML), or fine-tuning mind discussing esoteric idiosyncrasies the aspects of your existing skill set. language has; rewriting the PHP, MySQL, or Apache source code; or making theo- My definition of advanced PHP program- retically interesting but practically useless ming covers three loosely grouped areas: code. In short, I present to you several n Doing what you already do better, hundred pages of beyond-the-norm but faster, and more securely still absolutely necessary (and often cool) n Learning OOP tips and techniques. n Doing standard things using PHP and other technologies (like networking, unit testing, or XML) Introduction ix This book can be loosely divided into three Unlike with most of my other books, I do sections. The first three chapters cover not expect that you’ll necessarily read this advanced PHP knowledge in general: pro- book in sequential order, for the most part. gramming techniques, Web applications, Some chapters do assume that you’ve and databases. Those chapters all cover read others, like the object-oriented ones, information that the average PHP program- which have a progression to them. Some mer may not be familiar with but should be later chapters also reference examples able to comprehend. In the process, you’ll completed in earlier ones. If you read the pick up lots of useful code, too. later ones first, you’ll just need to skip The next six chapters focus on object- back over to the earlier ones to gener- oriented programming. This section ate whatever database or scripts the later constitutes about half of the book. OOP is chapter requires. explained starting with the fundamentals, Finally, I’ll be using HTML5 in my scripts then going into lots of advanced topics, and instead of HTML. I’ll also use some CSS, as ending with plenty of real-world examples. warranted. I do not discuss either of these The final five chapters are all “PHP and…” subjects in this book (and, to be frank, may chapters: not adhere to them perfectly).