PHP-Object-Oriented-Solutions.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
CYAN YELLOW MAGENTA BLACK In this book you’ll learn how to: Powers Produce code that’s easier to maintain by adopting OOP techniques. Use best practices by implementing basic design patterns. Simplify complex code through encapsulation. Unlock the secrets of the Standard PHP Library. PHP Generate your own news feed using Really Simple Syndication (RSS). O HP is easy to learn and a great way to add dynamic Through a series of practical projects, this book shows Pfunctionality to web sites, such as sending email from how OOP can be used to group related functions in a BJECT- online forms and generating database-driven content. portable manner. The projects include a validator for fil- But there soon comes a time when you realize you’re tering user input, a class that avoids the need to remember writing similar scripts over and over again. By adopting all the esoteric PHP date formatting codes, and an XML an object-oriented approach, you can avoid the need to generator—everyday requirements for a lot of develop- reinvent the wheel every time, creating scripts that are ers. Although the emphasis is on learning how the code reusable, easier to understand, and easier to maintain. works, if you’re in a hurry, the PHP classes used in the O book can be downloaded from the friends of ED web The main barrier to object-oriented programming (OOP) RIENTE site and incorporated into existing sites with a minimum is that it’s based on unfamiliar concepts, such as objects, of effort. classes, interfaces, encapsulation, and polymorphism. This book strips away the mystique and explains each The book is aimed at intermediate developers with a good concept in an approachable and understandable way. It understanding of PHP basics, such as variables, arrays, provides a gentle but fast-paced introduction to OOP functions, loops, and conditional statements. It provides as it applies to PHP. Another barrier to the adoption of the necessary groundwork for advancing on to using an OOP among PHP developers has been the slow migra- object-oriented framework, such as the Zend Framework, D tion from PHP 4, which used a radically different—and and taking your PHP coding skills to the next level. inferior—object model. Now that PHP 4 has come to the S official end of its life, this book concentrates exclusively OLUTIONS on using OOP with PHP 5 and 6. So you can be confi- Also Available Understand basic OOP concepts, dent that you’re learning skills that won’t be out of date such as inheritance, encapsulation, almost as soon as you put the book down. and polymorphism. Extend core PHP classes. Design and create your own classes for PHP 5 and 6. Available from Apress ISBN 978-1-4302-1011-5 SHELVING CATEGORY 5 3 6 9 9 1. PHP US $36.99 Mac/PC compatible www.friendsofed.com DAVID POWERS 9 781430 210115 http://foundationphp.com/ this print for reference only—size & color not accurate spine = 0.911" 392 page count 10115fm.qxd 7/22/08 12:10 PM Page i PHP Object-Oriented Solutions David Powers 10115fm.qxd 7/22/08 12:10 PM Page ii PHP Object-Oriented Solutions Copyright © 2008 by David Powers 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-1011-5 ISBN-13 (electronic): 978-1-4302-1012-2 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. 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 [email protected], or visit www.springeronline.com. For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705. Phone 510-549-5930, fax 510-549-5939, e-mail [email protected], 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 http://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 freely available to readers at www.friendsofed.com in the Downloads section. Credits Lead Editor Production Editor Ben Renow-Clarke Laura Esterman Technical Reviewer Compositor Seungyeob Choi Molly Sharp Editorial Board Proofreader Clay Andres, Steve Anglin, Ewan Buckingham, Patrick Vincent Tony Campbell, Gary Cornell, Jonathan Gennick, Matthew Moodie, Joseph Ottinger, Jeffrey Pepper, Indexer Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Toma Mulligan Matt Wade, Tom Welsh Project Manager Artist Beth Christmas April Milne Copy Editors Interior and Cover Designer Heather Lang and Damon Larson Kurt Krames Associate Production Director Manufacturing Director Kari Brooks-Copony Tom Debolski 10115fm.qxd 7/22/08 12:10 PM Page iii CONTENTS AT A GLANCE About the Author . xi About the Technical Reviewer . xiii Acknowledgments . xv Introduction . xvii Chapter 1: Why Object-Oriented PHP?. 3 Chapter 2: Writing PHP Classes. 23 Chapter 3: Taking the Pain Out of Working with Dates . 77 Chapter 4: Using PHP Filters to Validate User Input . 121 Chapter 5: Building a Versatile Remote File Connector . 169 Chapter 6: SimpleXML—Couldn’t Be Simpler . 207 Chapter 7: Supercharged Looping with SPL . 251 Chapter 8: Generating XML from a Database . 289 Chapter 9: Case Study: Creating Your Own RSS Feed . 321 Index. 355 10115fm.qxd 7/22/08 12:10 PM Page iv 10115fm.qxd 7/22/08 12:10 PM Page v CONTENTS About the Author . xi About the Technical Reviewer . xiii Acknowledgments . xv Introduction . xvii Chapter 1: Why Object-Oriented PHP?. 3 Understanding basic OOP concepts . 4 How OOP evolved . 5 Using classes and objects . 6 Protecting data integrity with encapsulation. 8 Polymorphism is the name of the game . 10 Extending classes through inheritance . 10 Deciding on a class hierarchy . 11 Using best practice . 12 How OOP has evolved in PHP . 13 OOP since PHP 5 . 13 Preparing for PHP 6 . 14 Choosing the right tools to work with PHP classes . 16 Using a specialized script editor . 16 Chapter review. 19 Chapter 2: Writing PHP Classes. 23 Formatting code for readability . 25 Using the Zend Framework PHP Coding Standard . 25 Choosing descriptive names for clarity . 26 Creating classes and objects . 26 Defining a class . 27 Controlling access to properties and methods . 27 Quick review . 32 Setting default values with a constructor method . 33 v 10115fm.qxd 7/22/08 12:10 PM Page vi CONTENTS Using inheritance to extend a class . 36 Defining a child class . 37 Accessing a parent class’s methods and properties . 39 Using the scope resolution operator . 39 Controlling changes to methods and properties . 44 Preventing a class or method from being overridden. 44 Using class constants for properties . 46 Creating static properties and methods . 47 Quick review . 49 Loading classes automatically. 50 Exploring advanced OOP features . 51 Creating abstract classes and methods . 52 Simulating multiple inheritance with interfaces . 54 Understanding which class an object is an instance of . 55 Restricting acceptable data with type hinting . 56 Using magic methods . 59 Converting an object to a string . 60 Cloning an object . 60 Accessing properties automatically . 64 Accessing methods automatically . 65 Cleaning up with a destructor method . 66 Handling errors with exceptions . 67 Throwing an exception . 67 Catching an exception . 67 Extracting information from an exception . 68 Extending the Exception class . 72 Using comments to generate code hints . 73 Writing PHPDoc comments. 74 Chapter review. 75 Chapter 3: Taking the Pain Out of Working with Dates . 77 Designing the class . 78 Examining the built-in date-related classes . 79 Using the DateTime class . 81 Setting the default time zone in PHP . 83 Examining the DateTimeZone class . 85 Using the DateTimeZone class. ..