this print for content only—size & color not accurate CYAN MAGENTA YELLOW BLACK PANTONE 123 C BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® Matt Zandstra, Author of Sams Teach Yourself PHP in 24 Hours US $44.99 Shelve in: PHP User level: Intermediate www.apress.com SOURCE CODE ONLINE Companion eBook See last page for details on $10 eBook version ISBN 978-1-4302-2925-4 9 781430 229254 5 44 9 9 PHP Objects, Patterns, and Practice THIRD EDITION Dear Reader, Over the past decade, PHP has embraced the object-oriented revolution. The language itself, the developers who work with it, and the applications they build, all increasingly share a focus on objects and object-oriented design. Another movement, separate but related, has taken root as well. That is the use of tools and techniques that help to ensure the success of projects, the efficacy of teams, and the quality of code. You’ll begin with an overview of PHP's object-oriented features, introducing key topics like class declaration, object instantiation, inheritance, and method and property encapsulation. You'll also learn about advanced topics including static methods and properties, abstract classes, interfaces, exception handling, object cloning, namespaces, closures and more. The next part of this book is devoted to design patterns, a vocabulary for applying elegant solutions to common problems in software development. You’ll learn about pattern concepts and discover how to implement several key pat- terns in your PHP applications. You’ll also find chapters on enterprise and data- base patterns. In the last section of this book, you will find practices and tools for managing your codebase and for collaborating with others in development. These include Phing, PHPUnit, phpDocumentor, PEAR, and Subversion. You’ll also learn how to use Continuous Integration, a system that brings all these tools together and automates them. I wrote PHP Objects, Patterns, and Practice to provide the kind of overview of code design and project practice I wish had been available when I first started to develop serious PHP applications. I hope this book inspires pleasure in coding and teaches you to build systems that are elegant in both design and management. Matt Zandstra THE APRESS ROADMAP Pro PHP: Patterns, Frameworks, Testing, and More PHP Objects, Patterns, and Practice, Third Edition Pro PHP Refactoring with Test Driven Design PHP Object-Oriented Solutions Pro PHP and jQuery Practical Web 2.0 Applications with PHP PHP for Absolute Beginners Beginning PHP and MySQL, Third Edition Zandstra Companion eBook Available PHP Objects, Patterns, and Practice 7.5 x 9.25 spine = 1.000" 536 page count THE EXPERT’S VOICE ® IN OPEN SOURCE THIRD EDITION Matt Zandstra Build powerful code by mastering PHP’s object-oriented enhancements, design patterns, and essential development tools THIRD EDITION PHP Objects, Patterns, and Practice Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. i PHP Objects, Patterns, and Practice Third Edition ■ ■ ■ Matt Zandstra Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ii PHP Objects, Patterns, and Practice, Third Edition Copyright © 2010 by Matt Zandstra All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2925-4 ISBN-13 (electronic): 978-1-4302-2926-1 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. President and Publisher: Paul Manning Lead Editor: Michelle Lowman, Matt Wade Technical Reviewer: Wes Hunt Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Jim Markham Copy Editor: Tracy Brown Collins Compositor: MacPS, LLC Indexer: Toma Mulligan Artist: April Milne Cover Designer: Anna Ischenko Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com , or visit www.springeronline.com. For information on translations, please e-mail info@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress 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 information contained in this work. The source code for this book is available to readers at www.apress.com. You will need to answer questions pertaining to this book in order to successfully download the code. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. iii Contents at a Glance ■Contents at a Glance iii ■Contents v ■About the Author xvii ■About the Technical Reviewer xviii ■Acknowledgments xix ■Introduction to the Third Edition xx Part 1: Introduction 1 ■Chapter 1: PHP: Design and Management 3 Part 2: Objects 9 ■Chapter 2: PHP and Objects 11 ■Chapter 3: Object Basics 15 ■Chapter 4: Advanced Features 41 ■Chapter 5: Object Tools 71 ■Chapter 6: Objects and Design 99 Part 3: Patterns 121 ■Chapter 7: What Are Design Patterns? Why Use Them? 123 ■Chapter 8: Some Pattern Principles 131 ■Chapter 9: Generating Objects 145 ■Chapter 10: Patterns for Flexible Object Programming 169 ■Chapter 11: Performing and Representing Tasks 189 ■Chapter 12: Enterprise Patterns 221 ■Chapter 13: Database Patterns 275 Part 4: Practice 315 ■Chapter 14: Good (and Bad) Practice 317 ■Chapter 15: An Introduction to PEAR and Pyrus 323 ■Chapter 16: Generating Documentation with phpDocumentor 347 ■Chapter 17: Version Control with Subversion 361 ■Chapter 18: Testing with PHPUnit 379 ■Chapter 19: Automated Build with Phing 407 ■Chapter 20: Continuous Integration 427 Part 5: Conclusion 451 ■Chapter 21: Objects, Patterns, Practice 453 ■Appendix A: Bibliography 463 ■Appendix B: A Simple Parser 467 ■Index 219 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. iv Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. v Contents ■Contents at a Glance iii ■Contents v ■About the Author xvii ■About the Technical Reviewer xviii ■Acknowledgments xix ■Introduction to the Third Edition xx Part 1: Introduction 1 ■Chapter 1: PHP: Design and Management 3 The Problem 3 PHP and Other Languages 4 About This Book 5 Objects 6 Patterns 6 Practice 6 What’s New in the Third Edition 7 Summary 7 Part 2: Objects 9 ■Chapter 2: PHP and Objects 11 The Accidental Success of PHP Objects 11 In the Beginning: PHP/FI 11 Syntactic Sugar: PHP 3 11 PHP 4 and the Quiet Revolution 12 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ■ CONTENTS vi Change Embraced: PHP 5 13 Into the Future 14 Advocacy and Agnosticism: The Object Debate 14 Summary 14 ■Chapter 3: Object Basics 15 Classes and Objects 15 A First Class 15 A First Object (or Two) 16 Setting Properties in a Class 17 Working with Methods 19 Creating a Constructor Method 21 Arguments and Types 22 Primitive Types 22 Taking the Hint: Object Types 25 Inheritance 27 The Inheritance Problem 27 Working with Inheritance 31 Public, Private, and Protected: Managing Access to Your Classes 35 Summary 39 ■Chapter 4: Advanced Features 41 Static Methods and Properties 41 Constant Properties 44 Abstract Classes 45 Interfaces 47 Late Static Bindings: The static Keyword 48 Handling Errors 51 Exceptions 52 Final Classes and Methods 57 Working with Interceptors 58 Defining Destructor Methods 62 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ■ CONTENTS vii Copying Objects with __clone() 63 Defining String Values for Your Objects 65 Callbacks, Anonymous Functions and Closures 66 Summary 70 ■Chapter 5: Object Tools 71 PHP and Packages 71 PHP Packages and Namespaces 71 Autoload 80 The Class and Object Functions 81 Looking for Classes 82 Learning About an Object or Class 83 Learning About Methods 84 Learning About Properties 85 Learning About Inheritance 85 Method Invocation 86 The Reflection API 87 Getting Started 87 Time to Roll Up Your Sleeves 88 Examining a Class 90 Examining Methods 91 Examining Method Arguments 93 Using the Reflection API 94 Summary 97 ■Chapter 6: Objects and Design 99 Defining Code Design 99 Object-Oriented and Procedural Programming 100 Responsibility 103 Cohesion 104 Coupling 104 Orthogonality 104 Choosing Your Classes 105 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ■ CONTENTS viii Polymorphism 106 Encapsulation 107 Forget How to Do It 108 Four Signposts 109 Code Duplication 109 The Class Who Knew Too Much 109 The Jack of All Trades 109 Conditional Statements 110 The UML 110 Class Diagrams 110 Sequence Diagrams 117 Summary 119 Part 3: Patterns 121 ■Chapter 7: What Are Design Patterns? Why Use Them? 123 What Are Design Patterns? 123 A Design Pattern Overview 125 Name 125 The Problem 125 The Solution 126 Consequences 126 The Gang of Four Format 126 Why Use Design Patterns? 127 A Design Pattern Defines a Problem 127 A Design Pattern Defines a Solution 127 Design Patterns Are Language Independent 127 Patterns Define a Vocabulary 127 Patterns Are Tried and Tested 128 Patterns Are Designed for Collaboration 128 Design Patterns Promote Good Design 128 PHP and Design Patterns 129 Summary 129 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... the success of a project Aside from this introduction and a brief conclusion, the book is divided into three main parts: objects, patterns, and practice Objects I begin Part 2 with a quick look at the history of PHP and objects, charting their shift from afterthought in PHP 3 to core feature in PHP 5 You can still be an experienced and successful PHP programmer with little or no knowledge of objects... development of PHP s object-oriented features We will look at • PHP/ FI 2.0: PHP, but not as we know it • PHP 3: Objects make their first appearance • PHP 4: Object-oriented programming grows up • PHP 5: Objects at the heart of the language • PHP 6: A glimpse of the future The Accidental Success of PHP Objects With so many object-oriented PHP libraries and applications in circulation, to say nothing of PHP 5’s... Matt Zandstra has worked as a web programmer, consultant, and writer for over a decade He is a senior developer at Yahoo, and a freelance coder and writer Matt is the author of Teach Yourself PHP in 24 Hours (SAMS) and a contributor to DHTML Unleashed (SAMS) He has written articles for Linux Magazine, Zend.com, IBM DeveloperWorks, and php| architect Magazine, among others He works primarily with PHP and. .. idea for PHP Objects, Patterns, and Practice, I felt I was swimming against the tide Many pattern implementations in PHP felt like glorified workarounds due to limitations in the language These days, though, it can be hard to keep up with pace of innovation in PHP objects, design, and project practice If that's a problem, well, it's the kind you want to have Especially if you have the tools at hand to... freelance PHP consultant Assessing and fixing a system like this can fund expensive espresso drinks and DVD box sets for six months or more More seriously, though, problems of this sort can mean the difference between a business’s success or failure PHP and Other Languages PHP s phenomenal popularity meant that its boundaries were tested early and hard As you will see in the next chapter, PHP started... architects of PHP 3 were Zeev Suraski and Andi Gutmans PHP 3 was a complete rewrite of PHP/ FI 2.0, but objects were not deemed a necessary part of the new syntax Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 11 CHAPTER 2 ■ PHP AND OBJECTS According to Zeev Suraski, support for classes was added almost as an afterthought (on 27 August 1997, to be precise) Classes and objects... explain objects, classes, and inheritance Even at this early stage, I look at some of the object enhancements that PHP 5 introduced The basics established, I delve deeper into our topic, examining PHP s more advanced objectoriented features I also devote a chapter to the tools that PHP provides to help you work with objects and classes It is not enough, though, to know how to declare a class, and to... Testing and build are all very well, but you have to install and run your tests, and keep on doing so in order to reap the benefits It’s easy to become complacent and let things slide if you don’t automate your builds and tests I look at some tools and techniques that are lumped together in the category “continuous integration” that will help you do just that What’s New in the Third Edition PHP is a... chapter, PHP s object support was by no means perfect, but with discipline and careful use of syntax, one could really think in objects and PHP at the same time Nevertheless, design disasters like the one depicted at the start of this chapter remained common Design culture was some way off, and almost nonexistent in books about PHP Online, though, the interest was clear Leon Atkinson wrote a piece about PHP. .. databases, processing forms, and flow control These tools were rewritten in C and combined under the name PHP/ FI 2.0 The language at this stage looked different from the syntax we recognize today, but not that different There was support for variables, associative arrays, and functions Objects, though, were not even on the horizon Syntactic Sugar: PHP 3 In fact, even as PHP 3 was in the planning stage, . management. Matt Zandstra THE APRESS ROADMAP Pro PHP: Patterns, Frameworks, Testing, and More PHP Objects, Patterns, and Practice, Third Edition Pro PHP Refactoring. Driven Design PHP Object-Oriented Solutions Pro PHP and jQuery Practical Web 2.0 Applications with PHP PHP for Absolute Beginners Beginning PHP and MySQL, Third