Modern PHP PHP is experiencing a renaissance, though it may be difficult to tell with all of “ For years I've struggled M the outdated PHP tutorials online. With this practical guide, you’ll learn how to recommend a PHP o PHP has become a full-featured, mature language with object-orientation, book that reflected d namespaces, and a growing collection of reusable component libraries. the current state of e Author Josh Lockhart—creator of PHP The Right Way, a popular initiative the language and r to encourage PHP best practices—reveals these new language features n in action. You’ll learn best practices for application architecture and community. With Modern planning, databases, security, testing, debugging, and deployment. If PHP, I finally have a title P you have a basic understanding of PHP and want to bolster your skills, I can endorse without H this is your book. hesitation.” P ■ Learn modern PHP features, such as namespaces, traits, —Ed Finkler generators, and closures Developer and author, Funkatron.com ■ Discover how to find, use, and create PHP components “ In programming, the ■ Follow best practices for application security, working only constant is change. withdatabases, errors and exceptions, and more PHP is changing, and ■ Learn tools and techniques for deploying, tuning, testing, and the way you develop profiling your PHP applications applications has to ■ Explore Facebook’s HVVM and Hack language Modern implementations—and how they affect modern PHP as well. Josh has laid ■ Build a local development environment that closely matches out the tools and your production server concepts that you need to be aware of to P HP Josh Lockhart created the Slim Framework, a popular PHP micro framework write modern PHP. that enables rapid web application and API development. He also started and currently curates PHP The Right Way, a popular initiative in the PHP commu- —Cal Evans nity that encourages good practices and disseminates quality information to PHP developers worldwide. He is a developer at New Media Campaigns in Carrboro, North Carolina. L o c k h a r t NEW FEATURES AND GOOD PRACTICES PHP Twitter: @oreillymedia facebook.com/oreilly US $29.99 CAN $34.99 ISBN: 978-1-491-90501-2 Josh Lockhart Modern PHP PHP is experiencing a renaissance, though it may be difficult to tell with all of “ For years I've struggled M the outdated PHP tutorials online. With this practical guide, you’ll learn how to recommend a PHP o PHP has become a full-featured, mature language with object-orientation, book that reflected d namespaces, and a growing collection of reusable component libraries. the current state of e Author Josh Lockhart—creator of PHP The Right Way, a popular initiative the language and r to encourage PHP best practices—reveals these new language features n in action. You’ll learn best practices for application architecture and community. With Modern planning, databases, security, testing, debugging, and deployment. If PHP, I finally have a title P you have a basic understanding of PHP and want to bolster your skills, I can endorse without H this is your book. hesitation.” P ■ Learn modern PHP features, such as namespaces, traits, —Ed Finkler generators, and closures Developer and author, Funkatron.com ■ Discover how to find, use, and create PHP components “ In programming, the ■ Follow best practices for application security, working with only constant is change. databases, errors and exceptions, and more PHP is changing, and ■ Learn tools and techniques for deploying, tuning, testing, and the way you develop profiling your PHP applications applications has to ■ Explore Facebook’s HVVM and Hack language Modern implementations—and how they affect modern PHP as well. Josh has laid ■ Build a local development environment that closely matches out the tools and your production server concepts that you need to be aware of to P HP Josh Lockhart created the Slim Framework, a popular PHP micro framework write modern PHP. that enables rapid web application and API development. He also started and currently curates PHP The Right Way, a popular initiative in the PHP commu- —Cal Evans nity that encourages good practices and disseminates quality information to PHP developers worldwide. He is a developer at New Media Campaigns in Carrboro, North Carolina. L o c k h a r t NEW FEATURES AND GOOD PRACTICES PHP Twitter: @oreillymedia facebook.com/oreilly US $29.99 CAN $34.99 ISBN: 978-1-491-90501-2 Josh Lockhart Modern PHP New Features and Good Practices Josh Lockhart Modern PHP by Josh Lockhart Copyright © 2015 Josh Lockhart. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editor: Allyson MacDonald Indexer: Judy McConville Production Editor: Nicole Shelby Interior Designer: David Futato Copyeditor: Phil Dangler Cover Designer: Ellie Volckhausen Proofreader: Eileen Cohen Illustrator: Rebecca Demarest February 2015: First Edition Revision History for the First Edition 2015-02-09: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491905012 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Modern PHP, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-90501-2 [LSI] For Laurel Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Part I. Language Features 1. The New PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Past 1 Present 2 Future 3 2. Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Namespaces 5 Why We Use Namespaces 7 Declaration 8 Import and Alias 9 Helpful Tips 11 Code to an Interface 13 Traits 17 Why We Use Traits 18 How to Create a Trait 19 How to Use a Trait 20 Generators 22 Create a Generator 22 Use a Generator 23 Closures 25 Create 25 Attach State 27 Zend OPcache 29 v Enable Zend OPcache 29 Configure Zend OPcache 31 Use Zend OPcache 31 Built-in HTTP server 31 Start the Server 32 Configure the Server 32 Router Scripts 33 Detect the Built-in Server 33 Drawbacks 33 What’s Next 34 Part II. Good Practices 3. Standards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 PHP-FIG to the Rescue 37 Framework Interoperability 38 Interfaces 38 Autoloading 39 Style 39 What Is a PSR? 40 PSR-1: Basic Code Style 40 PSR-2: Strict Code Style 41 PSR-3: Logger Interface 45 Write a PSR-3 Logger 46 Use a PSR-3 Logger 47 PSR-4: Autoloaders 47 Why Autoloaders Are Important 47 The PSR-4 Autoloader Strategy 48 How to Write a PSR-4 Autoloader (and Why You Shouldn’t) 49 4. Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Why Use Components? 51 What Are Components? 52 Components Versus Frameworks 53 Not All Frameworks Are Bad 54 Use the Right Tool for the Job 54 Find Components 55 Shop 56 Choose 56 Leave Feedback 57 Use PHP Components 57 vi | Table of Contents How to Install Composer 58 How to Use Composer 59 Example Project 61 Composer and Private Repositories 64 Create PHP Components 66 Vendor and Package Names 66 Namespaces 66 Filesystem Organization 67 The composer.json File 68 The README file 70 Component Implementation 71 Version Control 72 Packagist Submission 73 Using the Component 74 5. Good Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Sanitize, Validate, and Escape 75 Sanitize Input 76 Validate Data 79 Escape Output 80 Passwords 80 Never Know User Passwords 81 Never Restrict User Passwords 81 Never Email User Passwords 81 Hash User Passwords with bcrypt 82 Password Hashing API 82 Password Hashing API for PHP < 5.5.0 87 Dates, Times, and Time Zones 87 Set a Default Time Zone 88 The DateTime Class 88 The DateInterval Class 89 The DateTimeZone Class 91 The DatePeriod Class 92 The nesbot/carbon Component 93 Databases 93 The PDO Extension 93 Database Connections and DSNs 93 Prepared Statements 96 Query Results 98 Transactions 100 Multibyte Strings 103 Character Encoding 104 Table of Contents | vii Output UTF-8 Data 105 Streams 106 Stream Wrappers 106 Stream Context 109 Stream Filters 110 Custom Stream Filters 112 Errors and Exceptions 115 Exceptions 115 Exception Handlers 118 Errors 119 Error Handlers 121 Errors and Exceptions During Development 123 Production 124 Part III. Deployment, Testing, and Tuning 6. Hosting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Shared Server 129 Virtual Private Server 130 Dedicated Server 131 PaaS 131 Choose a Hosting Plan 132 7. Provisioning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Our Goal 134 Server Setup 134 First Login 134 Software Updates 135 Nonroot User 135 SSH Key-Pair Authentication 136 Disable Passwords and Root Login 138 PHP-FPM 138 Install 138 Global Configuration 139 Pool Configuration 140 nginx 143 Install 143 Virtual Host 143 Automate Server Provisioning 146 Delegate Server Provisioning 146 Further Reading 147 viii | Table of Contents