php objects patterns and practice

THE EXPERT’S VOICE ® IN OPEN SOURCE

PHP Objects,
Patterns, and
Practice
Build powerful code by mastering PHP’s
object-oriented enhancements, design patterns,
and essential development tools

THIRD EDITION
SOURCE CODE ONLINE

www.apress.com

Matt Zandstra

US $44.99

this print for content only—size & color not accurate

7.5 x 9.25 spine = 1.000" 536 page count


PHP Objects, Patterns,
and Practice
Third Edition

■■■
Matt Zandstra

i

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.

ii

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

iii

iv

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

v


■ CONTENTS

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


vi

■ CONTENTS

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


vii

■ CONTENTS

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

viii

■ CONTENTS

■Chapter 8: Some Pattern Principles ..................................................................131
The Pattern Revelation................................................................................................ 131
Composition and Inheritance ...................................................................................... 132
The Problem.......................................................................................................................................132
Using Composition .............................................................................................................................135

Decoupling .................................................................................................................. 137
The Problem.......................................................................................................................................137
Loosening Your Coupling ...................................................................................................................139

Code to an Interface, Not to an Implementation ......................................................... 141
The Concept That Varies ............................................................................................. 142
Patternitis.................................................................................................................... 143
The Patterns................................................................................................................ 143
Patterns for Generating Objects.........................................................................................................143
Patterns for Organizing Objects and Classes .....................................................................................143
Task-Oriented Patterns ......................................................................................................................143
Enterprise Patterns ............................................................................................................................144
Database Patterns..............................................................................................................................144

Summary..................................................................................................................... 144
■Chapter 9: Generating Objects ..........................................................................145
Problems and Solutions in Generating Objects........................................................... 145
The Singleton Pattern ................................................................................................. 149
The Problem.......................................................................................................................................149
Implementation ..................................................................................................................................150
Consequences....................................................................................................................................152

Factory Method Pattern .............................................................................................. 152
The Problem.......................................................................................................................................153
Implementation ..................................................................................................................................155
Consequences....................................................................................................................................157

Abstract Factory Pattern ............................................................................................. 157
The Problem.......................................................................................................................................158
Implementation ..................................................................................................................................159

ix

■ CONTENTS

Consequences....................................................................................................................................161
Prototype............................................................................................................................................162
The Problem.......................................................................................................................................163
Implementation ..................................................................................................................................163

But That’s Cheating! ................................................................................................... 166
Summary..................................................................................................................... 167
■Chapter 10: Patterns for Flexible Object Programming ....................................169
Structuring Classes to Allow Flexible Objects............................................................. 169
The Composite Pattern................................................................................................ 169
The Problem.......................................................................................................................................170
Implementation ..................................................................................................................................172
Consequences....................................................................................................................................175
Composite in Summary......................................................................................................................178

The Decorator Pattern................................................................................................. 179
The Problem.......................................................................................................................................179
Implementation ..................................................................................................................................181
Consequences....................................................................................................................................185

The Facade Pattern..................................................................................................... 185
The Problem.......................................................................................................................................185
Implementation ..................................................................................................................................186
Consequences....................................................................................................................................187

Summary..................................................................................................................... 187
■Chapter 11: Performing and Representing Tasks .............................................189
The Interpreter Pattern................................................................................................ 189
The Problem.......................................................................................................................................189
Implementation ..................................................................................................................................190
Interpreter Issues...............................................................................................................................197

The Strategy Pattern ................................................................................................... 198
The Problem.......................................................................................................................................198
Implementation ..................................................................................................................................199

The Observer Pattern .................................................................................................. 202

x

■ CONTENTS

Implementation ..................................................................................................................................204

The Visitor Pattern ...................................................................................................... 210
The Problem.......................................................................................................................................210
Implementation ..................................................................................................................................211
Visitor Issues......................................................................................................................................215

The Command Pattern ................................................................................................ 216
The Problem.......................................................................................................................................216
Implementation ..................................................................................................................................216

Summary..................................................................................................................... 220
■Chapter 12: Enterprise Patterns........................................................................221
Architecture Overview................................................................................................. 221
The Patterns.......................................................................................................................................222
Applications and Layers.....................................................................................................................222

Cheating Before We Start............................................................................................ 225
Registry..............................................................................................................................................225
Implementation ..................................................................................................................................226

The Presentation Layer ............................................................................................... 235
Front Controller ..................................................................................................................................235
Application Controller.........................................................................................................................245
Page Controller ..................................................................................................................................257
Template View and View Helper ........................................................................................................262

The Business Logic Layer ........................................................................................... 264
Transaction Script..............................................................................................................................265
Domain Model ....................................................................................................................................269

Summary..................................................................................................................... 273
■Chapter 13: Database Patterns .........................................................................275
The Data Layer ............................................................................................................ 275
Data Mapper ............................................................................................................... 275
The Problem.......................................................................................................................................276
Implementation ..................................................................................................................................276
Consequences....................................................................................................................................287

xi

■ CONTENTS

Identity Map ................................................................................................................ 288
The Problem.......................................................................................................................................288
Implementation ..................................................................................................................................289
Consequences....................................................................................................................................291

Unit of Work ................................................................................................................ 291
The Problem.......................................................................................................................................292
Implementation ..................................................................................................................................292
Consequences....................................................................................................................................296
Lazy Load ...........................................................................................................................................296
The Problem.......................................................................................................................................296
Implementation ..................................................................................................................................297
Consequences....................................................................................................................................298

Domain Object Factory................................................................................................ 298
The Problem.......................................................................................................................................298
Implementation ..................................................................................................................................299
Consequences....................................................................................................................................300

The Identity Object ...................................................................................................... 301
The Problem.......................................................................................................................................301
Implementation ..................................................................................................................................302
Consequences....................................................................................................................................307

The Selection Factory and Update Factory Patterns ................................................... 307
The Problem.......................................................................................................................................307
Implementation ..................................................................................................................................307
Consequences....................................................................................................................................311

What’s Left of Data Mapper Now? .............................................................................. 311
Summary..................................................................................................................... 313
Part 4: Practice ....................................................................................................315
■Chapter 14: Good (and Bad) Practice ................................................................317
Beyond Code ............................................................................................................... 317
Borrowing a Wheel..................................................................................................... 317
Playing Nice ................................................................................................................ 319

xii

■ CONTENTS

Giving Your Code Wings .............................................................................................. 319
Documentation............................................................................................................ 320
Testing ........................................................................................................................ 321
Continuous Integration................................................................................................ 322
Summary..................................................................................................................... 322
■Chapter 15: An Introduction to PEAR and Pyrus ...............................................323
What Is PEAR?............................................................................................................. 323
Phar Out with Pyrus .................................................................................................... 324
Installing a Package................................................................................................... 326
PEAR Channels...................................................................................................................................327

Using a PEAR Package................................................................................................ 329
Handling PEAR Errors.........................................................................................................................331

Creating Your Own PEAR Package .............................................................................. 334
package.xml.......................................................................................................................................334
Package Elements..............................................................................................................................334
The contents Element .....................................................................................................................336
Dependencies ....................................................................................................................................339
Tweaking Installation with phprelease ...........................................................................................340
Preparing a Package for Shipment ....................................................................................................341
Setting Up Your Own Channel ............................................................................................................341

Summary..................................................................................................................... 346
■Chapter 16: Generating Documentation with phpDocumentor..........................347
Why Document?.......................................................................................................... 347
Installation .................................................................................................................. 348
Generating Documentation ......................................................................................... 349
DocBlock Comments................................................................................................... 350
Documenting Classes ................................................................................................. 352
File-Level Documentation ........................................................................................... 353
Documenting Properties ............................................................................................. 353
Documenting Methods................................................................................................ 355

xiii

■ CONTENTS

Creating Links in Documentation................................................................................ 356
Summary..................................................................................................................... 359
■Chapter 17: Version Control with Subversion ...................................................361
Why Use Version Control?........................................................................................... 361
Getting Subversion...................................................................................................... 362
Configuring a Subversion Repository.......................................................................... 363
Creating a Repository.........................................................................................................................363

Beginning a Project..................................................................................................... 364
Updating and Committing ........................................................................................... 368
Adding and Removing Files and Directories ............................................................... 371
Adding a File ......................................................................................................................................371
Removing a File .................................................................................................................................372
Adding a Directory .............................................................................................................................372
Removing Directories.........................................................................................................................373

Tagging and Exporting a Release ............................................................................... 373
Tagging a Project ...............................................................................................................................373
Exporting a Project.............................................................................................................................374

Branching a Project..................................................................................................... 374
Summary..................................................................................................................... 378
■Chapter 18: Testing with PHPUnit .....................................................................379
Functional Tests and Unit Tests.................................................................................. 379
Testing by Hand .......................................................................................................... 380
Introducing PHPUnit .................................................................................................... 382
Creating a Test Case ..........................................................................................................................382
Assertion Methods .............................................................................................................................383
Testing Exceptions .............................................................................................................................384
Running Test Suites ...........................................................................................................................385
Constraints.........................................................................................................................................386
Mocks and Stubs ...............................................................................................................................388
Tests Succeed When They Fail ..........................................................................................................391

xiv

■ CONTENTS

Writing Web Tests....................................................................................................... 394
Refactoring a Web Application for Testing.........................................................................................394
Simple Web Testing ...........................................................................................................................397
Introducing Selenium .........................................................................................................................398

A Note of Caution ........................................................................................................ 403
Summary..................................................................................................................... 405
■Chapter 19: Automated Build with Phing ..........................................................407
What Is Phing? ............................................................................................................ 407
Getting and Installing Phing ........................................................................................ 408
Composing the Build Document.................................................................................. 408
Targets ...............................................................................................................................................410
Properties...........................................................................................................................................412
Types..................................................................................................................................................416
Tasks..................................................................................................................................................421

Summary.............................................................................................................