Matt Zandstra

PHP Objects, Patterns, and Practice

5th ed.

Matt Zandstra

Liverpool, Merseyside, UK

Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter.

ISBN 978-1-4842-1995-9

e-ISBN 978-1-4842-1996-6

DOI 10.1007/978-1-4842-1996-6

Library of Congress Control Number: 2016961297

© Matt Zandstra 2016

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 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.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

For Louise, who is the whole point.

Introduction

When I first conceived of this book, object-oriented design in PHP was an esoteric topic. The intervening years have not only seen the inexorable rise of PHP as an object-oriented language, but also the march of the framework. Frameworks are incredibly useful, of course. They manage the guts and the glue of many (perhaps, these days, most) web applications. What’s more, they often exemplify precisely the principles of design that this book explores.

There is, though, a danger for developers here, as there is in all useful APIs. This is the fear that one might find oneself relegated to userland, forced to wait for remote gurus to fix bugs or add features at their whim. It’s a short step from this standpoint to a kind of exile in which one is left regarding the innards of a framework as advanced magic, and one’s own work as not much more than a minor adornment stuck up on top of a mighty unknowable infrastructure.

Although I’m an inveterate reinventor of wheels, the thrust of my argument is not that we should all throw away our frameworks and build MVC applications from scratch (at least not always). It is rather that, as developers, we should understand the problems that frameworks solve, and the strategies they use to solve them. We should be able to evaluate frameworks not only functionally but in terms of the design decisions their creators have made, and to judge the quality of their implementations. And yes, when the conditions are right, we should go ahead and build our own spare and focused applications, and, over time, compile our own libraries of reusable code.

I hope this book goes some way toward helping PHP developers apply design-oriented insights to their platforms and libraries, and provides some the conceptual tools needed when it’s time to go it alone.

Acknowledgments

As always, I have benefited from the support of many people while working on this edition. But as always, I must also look back to the book’s origins. I tried out some of this book’s underlying concepts in a talk in Brighton, back when we were all first marveling at the shiny possibilities of PHP 5. Thanks to Andy Budd, who hosted the talk, and to the vibrant Brighton developer community. Thanks also to Jessey White-Cinis, who was at that meeting and who put me in touch with Martin Streicher at Apress.

Once again, this time around the Apress team has provided enormous support, feedback, and encouragement. I am lucky to have benefited from such professionalism.

When I proposed this edition, I blithely promised I would update all the code to comply with the latest style guidelines. I’m very lucky to have had my friend and colleague, Paul Tregoing, working on this edition as Technical Reviewer. Not only has he kept me to my commitment, he has waded into the code itself to zap many, many standards violations, showing commitment above and beyond the call of duty! Furthermore, this edition has greatly benefited from Paul’s knowledge, insight, and attention to detail—many thanks Paul!

Thanks and love to my wife, Louise, and to our children, Holly and Jake, for many much needed distractions. Thanks to Steven Metsker for his kind permission to reimplement in PHP a simplified version of the parser API he presented in his book, Building Parsers in Java (Addison-Wesley Professional, 2001).

I write to music and, in previous editions of this book, I remembered the great DJ, John Peel, champion of the underground and the eclectic. The soundtrack for this edition was largely provided by BBC Radio 3’s contemporary music show, Late Junction, played on a loop. Thanks to them for keeping things weird.

Contents

  1. Part I: Objects
    1. Chapter 1:​ PHP:​ Design and Management
      1. The Problem
      2. PHP and Other Languages
      3. About This Book
        1. Objects
        2. Patterns
        3. Practice
        4. What’s New in the Fifth Edition
      4. Summary
    2. Chapter 2:​ PHP and Objects
      1. The Accidental Success of PHP Objects
        1. In the Beginning:​ PHP/​FI
        2. Syntactic Sugar:​ PHP 3
        3. PHP 4 and the Quiet Revolution
        4. Change Embraced:​ PHP 5
        5. PHP 7:​ Closing the Gap
      2. Advocacy and Agnosticism:​ The Object Debate
      3. Summary
    3. Chapter 3:​ Object Basics
      1. Classes and Objects
        1. A First Class
        2. A First Object (or Two)
      2. Setting Properties in a Class
      3. Working with Methods
        1. Creating a Constructor Method
      4. Arguments and Types
        1. Primitive Types
        2. Taking the Hint:​ Object Types
      5. Inheritance
        1. The Inheritance Problem
        2. Working with Inheritance
        3. Public, Private, and Protected:​ Managing Access to Your Classes
      6. Summary
    4. Chapter 4:​ Advanced Features
      1. Static Methods and Properties
      2. Constant Properties
      3. Abstract Classes
      4. Interfaces
      5. Traits
        1. A Problem for Traits to Solve
        2. Defining and Using a Trait
        3. Using More than One Trait
        4. Combining Traits and Interfaces
        5. Managing Method Name Conflicts with insteadof
        6. Aliasing overridden trait methods
        7. Using static methods in traits
        8. Accessing Host Class Properties
        9. Defining Abstract Methods in Traits
        10. Changing Access Rights to Trait Methods
      6. Late Static Bindings:​ The static Keyword
      7. Handling Errors
        1. Exceptions
      8. Final Classes and Methods
      9. The Internal Error Class
      10. Working with Interceptors
      11. Defining Destructor Methods
      12. Copying Objects with _​_​clone()
      13. Defining String Values for Your Objects
      14. Callbacks, Anonymous Functions, and Closures
      15. Anonymous Classes
      16. Summary
    5. Chapter 5:​ Object Tools
      1. PHP and Packages
        1. PHP Packages and Namespaces
        2. Autoload
      2. The Class and Object Functions
        1. Looking for Classes
        2. Learning About an Object or Class
        3. Getting a Fully Qualified String Reference to a Class
        4. Learning About Methods
        5. Learning About Properties
        6. Learning About Inheritance
        7. Method Invocation
      3. The Reflection API
        1. Getting Started
        2. Time to Roll up Your Sleeves
        3. Examining a Class
        4. Examining Methods
        5. Examining Method Arguments
        6. Using the Reflection API
      4. Summary
    6. Chapter 6:​ Objects and Design
      1. Defining Code Design
      2. Object-Oriented and Procedural Programming
        1. Responsibility
        2. Cohesion
        3. Coupling
        4. Orthogonality
      3. Choosing Your Classes
      4. Polymorphism
      5. Encapsulation
      6. Forget How to Do It
      7. Four Signposts
        1. Code Duplication
        2. The Class Who Knew Too Much
        3. The Jack of All Trades
        4. Conditional Statements
      8. The UML
        1. Class Diagrams
        2. Sequence Diagrams
      9. Summary
  2. Part II: Patterns
    1. Chapter 7:​ What Are Design Patterns?​ Why Use Them?​
      1. What Are Design Patterns?​
      2. A Design Pattern Overview
        1. Name
        2. The Problem
        3. The Solution
        4. Consequences
      3. The Gang of Four Format
      4. Why Use Design Patterns?​
        1. A Design Pattern Defines a Problem
        2. A Design Pattern Defines a Solution
        3. Design Patterns Are Language Independent
        4. Patterns Define a Vocabulary
        5. Patterns Are Tried and Tested
        6. Patterns Are Designed for Collaboration
        7. Design Patterns Promote Good Design
        8. Design Patterns are Used By Popular Frameworks
      5. PHP and Design Patterns
      6. Summary
    2. Chapter 8:​ Some Pattern Principles
      1. The Pattern Revelation
      2. Composition and Inheritance
        1. The Problem
        2. Using Composition
      3. Decoupling
        1. The Problem
        2. Loosening Your Coupling
      4. Code to an Interface, Not to an Implementation
      5. The Concept that Varies
      6. Patternitis
      7. The Patterns
        1. Patterns for Generating Objects
        2. Patterns for Organizing Objects and Classes
        3. Task-Oriented Patterns
        4. Enterprise Patterns
        5. Database Patterns
      8. Summary
    3. Chapter 9:​ Generating Objects
      1. Problems and Solutions in Generating Objects
      2. The Singleton Pattern
        1. The Problem
        2. Implementation
        3. Consequences
      3. Factory Method Pattern
        1. The Problem
        2. Implementation
        3. Consequences
      4. Abstract Factory Pattern
        1. The Problem
        2. Implementation
        3. Consequences
      5. Prototype
        1. The Problem
        2. Implementation
      6. Pushing to the Edge:​ Service Locator
      7. Splendid Isolation:​ Dependency Injection
        1. The Problem
        2. Implementation
        3. Consequences
      8. Summary
    4. Chapter 10:​ Patterns for Flexible Object Programming
      1. Structuring Classes to Allow Flexible Objects
      2. The Composite Pattern
        1. The Problem
        2. Implementation
        3. Consequences
        4. Composite in Summary
      3. The Decorator Pattern
        1. The Problem
        2. Implementation
        3. Consequences
      4. The Facade Pattern
        1. The Problem
        2. Implementation
        3. Consequences
      5. Summary
    5. Chapter 11:​ Performing and Representing Tasks
      1. The Interpreter Pattern
        1. The Problem
        2. Implementation
        3. Interpreter Issues
      2. The Strategy Pattern
        1. The Problem
        2. Implementation
      3. The Observer Pattern
        1. Implementation
      4. The Visitor Pattern
        1. The Problem
        2. Implementation
        3. Visitor Issues
      5. The Command Pattern
        1. The Problem
        2. Implementation
      6. The Null Object Pattern
        1. The Problem
        2. Implementation
      7. Summary
    6. Chapter 12:​ Enterprise Patterns
      1. Architecture Overview
        1. The Patterns
        2. Applications and Layers
      2. Cheating Before We Start
        1. Registry
        2. Implementation
      3. The Presentation Layer
        1. Front Controller
        2. Application Controller
        3. Page Controller
        4. Template View and View Helper
      4. The Business Logic Layer
        1. Transaction Script
        2. Domain Model
      5. Summary
    7. Chapter 13:​ Database Patterns
      1. The Data Layer
      2. Data Mapper
        1. The Problem
        2. Implementation
        3. Consequences
      3. Identity Map
        1. The Problem
        2. Implementation
        3. Consequences
      4. Unit of Work
        1. The Problem
        2. Implementation
        3. Consequences
        4. Lazy Load
        5. The Problem
        6. Implementation
        7. Consequences
      5. Domain Object Factory
        1. The Problem
        2. Implementation
        3. Consequences
      6. The Identity Object
        1. The Problem
        2. Implementation
        3. Consequences
      7. The Selection Factory and Update Factory Patterns
        1. The Problem
        2. Implementation
        3. Consequences
      8. What’s Left of Data Mapper Now?​
      9. Summary
  3. Part III: Practice
    1. Chapter 14:​ Good (and Bad) Practice
      1. Beyond Code
      2. Borrowing a Wheel
      3. Playing Nice
      4. Giving Your Code Wings
      5. Standards
      6. Vagrant
      7. Testing
      8. Continuous Integration
      9. Summary
    2. Chapter 15:​ PHP Standards
      1. Why Standards?​
      2. What Are PHP Standards Recommendations?​
        1. Why PSR in Particular?​
        2. Who Are PSRs for?​
      3. Coding with Style
        1. PSR-1 Basic Coding Standard
        2. PSR-2 Coding Style Guide
        3. Checking and Fixing your Code
      4. PSR-4 Autoloading
        1. The Rules that Matter to Us
      5. Summary
    3. Chapter 16:​ PHP Using and Creating Components with Composer
      1. What Is Composer?​
      2. Installing Composer
      3. Installing a (Set of) Package(s)
        1. Installing a Package from the Command Line
        2. Versions
        3. require-dev
      4. Composer and Autoload
      5. Creating Your Own Package
        1. Adding Package Information
        2. Platform Packages
      6. Distribution Through Packagist
      7. Keeping it private
      8. Summary
    4. Chapter 17:​ Version Control with Git
      1. Why Use Version Control?​
      2. Getting Git
      3. Using an Online Git Repository
      4. Configuring a Git Server
        1. Creating the Remote Repository
      5. Beginning a Project
        1. Cloning the Repository
      6. Updating and Committing
      7. Adding and Removing Files and Directories
        1. Adding a File
        2. Removing a File
        3. Adding a Directory
        4. Removing Directories
      8. Tagging a Release
      9. Branching a Project
      10. Summary
    5. Chapter 18:​ Testing with PHPUnit
      1. Functional Tests and Unit Tests
      2. Testing by Hand
      3. Introducing PHPUnit
        1. Creating a Test Case
        2. Assertion Methods
        3. Testing Exceptions
        4. Running Test Suites
        5. Constraints
        6. Mocks and Stubs
        7. Tests Succeed When They Fail
      4. Writing Web Tests
        1. Refactoring a Web Application for Testing
        2. Simple Web Testing
        3. Introducing Selenium
      5. A Note of Caution
      6. Summary
    6. Chapter 19:​ Automated Build with Phing
      1. What Is Phing?​
      2. Getting and Installing Phing
      3. Composing the Build Document
        1. Targets
        2. Properties
        3. Types
        4. Tasks
      4. Summary
    7. Chapter 20:​ Vagrant
      1. The Problem
      2. A Little Setup
        1. Choosing and Installing a Vagrant Box
      3. Mounting Local Directories on the Vagrant Box
      4. Provisioning
        1. Setting Up the Web Server
        2. Setting Up MySQL
        3. Configuring a Host Name
      5. Wrapping It Up
      6. Summary
    8. Chapter 21:​ Continuous Integration
      1. What Is Continuous Integration?​
        1. Preparing a Project for CI
        2. Installing Jenkins Plug-ins
        3. Setting up the Git Public Key
        4. Installing a Project
        5. Running the First Build
        6. Configuring the Reports
        7. Triggering Builds
      2. Summary
    9. Chapter 22:​ Objects, Patterns, Practice
      1. Objects
        1. Choice
        2. Encapsulation and Delegation
        3. Decoupling
        4. Reusability
        5. Aesthetics
      2. Patterns
        1. What Patterns Buy Us
        2. Patterns and Principles of Design
      3. Practice
        1. Testing
        2. Standards
        3. Version Control
        4. Automated Build
        5. Continuous Integration
        6. What I Missed
      4. Summary
    10. Chapter 23:​ Appendix A:​ Bibliography
      1. Books
      2. Articles
      3. Sites
    11. Chapter 24:​ Appendix B:​ A Simple Parser
      1. The Scanner
      2. The Parser
  4. Index

About the Author and About the Technical Reviewer

About the Author

Matt Zandstra has worked as a web programmer, consultant, and writer for over two decades. He was a senior developer at Yahoo! working both in London and Silicon Valley. He now earns his living as a freelance consultant and writer. Before writing PHP Objects, Patterns, and Practice , he was the author of three editions of SAMS Teach Yourself PHP in 24 Hours (Sams Publishing, 1999) and a contributor to DHTML Unleashed (Sams.net Publishing, 1997). He has written articles for Linux Magazine , Zend.com, IBM DeveloperWorks, and php|architect Magazine , among others. Matt also studies literature and writes fiction. He holds MA degrees in Creative Writing from both Manchester University and the University of East Anglia. When he’s not studying or freelancing at various locations around the UK, Matt lives in Brighton with his wife, Louise, and two children, Holly and Jake.

About the Technical Reviewer

A314621_5_En_BookFrontmatter_Figb_HTML.jpg

Paul Tregoing has worked in ops and development in a variety of environments for nearly twenty years. He worked at Yahoo! for five years as a senior developer on the frontpage team, there he generated his first PHP using Perl. Other employers include Bloomberg, Schlumberger and the British Antarctic Survey, where he became intimate with thousands of penguins.

He now works as a freelance engineer for various clients, small and large, building multi-tiered web apps using PHP, Javascript, and many other technologies. Paul is a voracious consumer of science fiction and fantasy, and harbours not-so-secret ambitions to try his hand at writing in the near future. He lives in Cambridge, UK with this wife and children.