Anda di halaman 1dari 16

Modern PHP

Author Josh Lockhartcreator of PHP The Right Way, a popular initiative


to encourage PHP best practicesreveals these new language features
in action. Youll learn best practices for application architecture and
planning, databases, security, testing, debugging, and deployment. If
you have a basic understanding of PHP and want to bolster your skills,
this is your book.

Learn modern PHP features, such as namespaces, traits,


generators, and closures

Discover how to find, use, and create PHP components

Follow best practices for application security, working


withdatabases, errors and exceptions, and more

Learn tools and techniques for deploying, tuning, testing, and


profiling your PHP applications

Explore Facebooks HVVM and Hack language


implementationsand how they affect modern PHP

Build a local development environment that closely matches


your production server

Josh Lockhart created the Slim Framework, a popular PHP micro framework
that enables rapid web application and API development. He also started and
currently curates PHP The Right Way, a popular initiative in the PHP community that encourages good practices and disseminates quality information to PHP
developers worldwide. He is a developer at New Media Campaigns in Carrboro,
North Carolina.

US $29.99

book that reflected


the current state of
the language and
community. With Modern
PHP, I finally have a title
I can endorse without
hesitation.

Ed Finkler

Developer and author, Funkatron.com

the
Inonlyprogramming,
constant is change.
PHP is changing, and
the way you develop
applications has to
as well. Josh has laid
out the tools and
concepts that you
need to be aware of to
write modern PHP.

Modern

Cal Evans

Twitter: @oreillymedia
facebook.com/oreilly

Lockhart

PHP

years I've struggled


For
to recommend a PHP

Modern PHP

PHP is experiencing a renaissance, though it may be difficult to tell with all of


the outdated PHP tutorials online. With this practical guide, youll learn how
PHP has become a full-featured, mature language with object-orientation,
namespaces, and a growing collection of reusable component libraries.

PHP

NEW FEATURES AND GOOD PRACTICES

CAN $34.99

ISBN: 978-1-491-90501-2

Josh Lockhart

Modern PHP

Author Josh Lockhartcreator of PHP The Right Way, a popular initiative


to encourage PHP best practicesreveals these new language features
in action. Youll learn best practices for application architecture and
planning, databases, security, testing, debugging, and deployment. If
you have a basic understanding of PHP and want to bolster your skills,
this is your book.

Learn modern PHP features, such as namespaces, traits,


generators, and closures

Discover how to find, use, and create PHP components

Follow best practices for application security, working with


databases, errors and exceptions, and more

Learn tools and techniques for deploying, tuning, testing, and


profiling your PHP applications

Explore Facebooks HVVM and Hack language


implementationsand how they affect modern PHP

Build a local development environment that closely matches


your production server

Josh Lockhart created the Slim Framework, a popular PHP micro framework
that enables rapid web application and API development. He also started and
currently curates PHP The Right Way, a popular initiative in the PHP community that encourages good practices and disseminates quality information to PHP
developers worldwide. He is a developer at New Media Campaigns in Carrboro,
North Carolina.

US $29.99

book that reflected


the current state of
the language and
community. With Modern
PHP, I finally have a title
I can endorse without
hesitation.

Ed Finkler

Developer and author, Funkatron.com

the
Inonlyprogramming,
constant is change.
PHP is changing, and
the way you develop
applications has to
as well. Josh has laid
out the tools and
concepts that you
need to be aware of to
write modern PHP.

Modern

Cal Evans

Twitter: @oreillymedia
facebook.com/oreilly

Lockhart

PHP

years I've struggled


For
to recommend a PHP

Modern PHP

PHP is experiencing a renaissance, though it may be difficult to tell with all of


the outdated PHP tutorials online. With this practical guide, youll learn how
PHP has become a full-featured, mature language with object-orientation,
namespaces, and a growing collection of reusable component libraries.

PHP

NEW FEATURES AND GOOD PRACTICES

CAN $34.99

ISBN: 978-1-491-90501-2

Josh Lockhart

OReilly EbooksYour bookshelf on your devices!

When you buy an ebook through oreilly.com you get lifetime access to the book, and
whenever possible we provide it to you in five, DRM-free file formatsPDF, .epub,
Kindle-compatible .mobi, Android .apk, and DAISYthat you can use on the devices of
your choice. Our ebook files are fully searchable, and you can cut-and-paste and print
them. We also alert you when weve updated the files with corrections and additions.

Learn more at ebooks.oreilly.com


You can also purchase OReilly ebooks through the
iBookstore, the Android Marketplace, and Amazon.com.

Spreading the knowledge of innovators

oreilly.com

Modern PHP
by Josh Lockhart
Copyright 2015 Josh Lockhart. All rights reserved.
Printed in the United States of America.
Published by OReilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
OReilly 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 corporate@oreilly.com.

Editor: Allyson MacDonald


Production Editor: Nicole Shelby
Copyeditor: Phil Dangler
Proofreader: Eileen Cohen
February 2015:

Indexer: Judy McConville


Interior Designer: David Futato
Cover Designer: Ellie Volckhausen
Illustrator: Rebecca Demarest

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 OReilly logo is a registered trademark of OReilly Media, Inc. Modern PHP, the cover image, and
related trade dress are trademarks of OReilly 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]

Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Part I.

Language Features

1. The New PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


Past
Present
Future

1
2
3

2. Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Namespaces
Why We Use Namespaces
Declaration
Import and Alias
Helpful Tips
Code to an Interface
Traits
Why We Use Traits
How to Create a Trait
How to Use a Trait
Generators
Create a Generator
Use a Generator
Closures
Create
Attach State
Zend OPcache

5
7
8
9
11
13
17
18
19
20
22
22
23
25
25
27
29

Enable Zend OPcache


Configure Zend OPcache
Use Zend OPcache
Built-in HTTP server
Start the Server
Configure the Server
Router Scripts
Detect the Built-in Server
Drawbacks
Whats Next

Part II.

29
31
31
31
32
32
33
33
33
34

Good Practices

3. Standards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
PHP-FIG to the Rescue
Framework Interoperability
Interfaces
Autoloading
Style
What Is a PSR?
PSR-1: Basic Code Style
PSR-2: Strict Code Style
PSR-3: Logger Interface
Write a PSR-3 Logger
Use a PSR-3 Logger
PSR-4: Autoloaders
Why Autoloaders Are Important
The PSR-4 Autoloader Strategy
How to Write a PSR-4 Autoloader (and Why You Shouldnt)

37
38
38
39
39
40
40
41
45
46
47
47
47
48
49

4. Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Why Use Components?
What Are Components?
Components Versus Frameworks
Not All Frameworks Are Bad
Use the Right Tool for the Job
Find Components
Shop
Choose
Leave Feedback
Use PHP Components

vi

Table of Contents

51
52
53
54
54
55
56
56
57
57

How to Install Composer


How to Use Composer
Example Project
Composer and Private Repositories
Create PHP Components
Vendor and Package Names
Namespaces
Filesystem Organization
The composer.json File
The README file
Component Implementation
Version Control
Packagist Submission
Using the Component

58
59
61
64
66
66
66
67
68
70
71
72
73
74

5. Good Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Sanitize, Validate, and Escape
Sanitize Input
Validate Data
Escape Output
Passwords
Never Know User Passwords
Never Restrict User Passwords
Never Email User Passwords
Hash User Passwords with bcrypt
Password Hashing API
Password Hashing API for PHP < 5.5.0
Dates, Times, and Time Zones
Set a Default Time Zone
The DateTime Class
The DateInterval Class
The DateTimeZone Class
The DatePeriod Class
The nesbot/carbon Component
Databases
The PDO Extension
Database Connections and DSNs
Prepared Statements
Query Results
Transactions
Multibyte Strings
Character Encoding

75
76
79
80
80
81
81
81
82
82
87
87
88
88
89
91
92
93
93
93
93
96
98
100
103
104

Table of Contents

vii

Output UTF-8 Data


Streams
Stream Wrappers
Stream Context
Stream Filters
Custom Stream Filters
Errors and Exceptions
Exceptions
Exception Handlers
Errors
Error Handlers
Errors and Exceptions During Development
Production

Part III.

105
106
106
109
110
112
115
115
118
119
121
123
124

Deployment, Testing, and Tuning

6. Hosting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Shared Server
Virtual Private Server
Dedicated Server
PaaS
Choose a Hosting Plan

129
130
131
131
132

7. Provisioning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Our Goal
Server Setup
First Login
Software Updates
Nonroot User
SSH Key-Pair Authentication
Disable Passwords and Root Login
PHP-FPM
Install
Global Configuration
Pool Configuration
nginx
Install
Virtual Host
Automate Server Provisioning
Delegate Server Provisioning
Further Reading

viii

Table of Contents

134
134
134
135
135
136
138
138
138
139
140
143
143
143
146
146
147

Whats Next

147

8. Tuning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
The php.ini File
Memory
Zend OPcache
File Uploads
Max Execution Time
Session Handling
Output Buffering
Realpath Cache
Up Next

149
150
151
152
153
154
155
155
155

9. Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Version Control
Automate Deployment
Make It Simple
Make It Predictable
Make It Reversible
Capistrano
How It Works
Install
Configure
Authenticate
Prepare the Remote Server
Capistrano Hooks
Deploy Your Application
Roll Back Your Application
Further Reading
Whats Next

157
157
158
158
158
158
158
159
159
161
161
162
163
163
163
163

10. Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165


Why Do We Test?
When Do We Test?
Before
During
After
What Do We Test?
How Do We Test?
Unit Tests
Test-Driven Development (TDD)
Behavior-Driven Development (BDD)

165
166
166
166
166
166
167
167
167
167

Table of Contents

ix

PHPUnit
Directory Structure
Install PHPUnit
Install Xdebug
Configure PHPUnit
The Whovian Class
The WhovianTest Test Case
Run Tests
Code Coverage
Continuous Testing with Travis CI
Setup
Run
Further Reading
Whats Next

168
169
170
170
171
172
173
175
176
177
177
178
178
179

11. Profiling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181


When to Use a Profiler
Types of Profilers
Xdebug
Configure
Trigger
Analyze
XHProf
Install
XHGUI
Configure
Trigger
New Relic Profiler
Blackfire Profiler
Further Reading
Whats Next

181
181
182
182
183
183
183
184
184
185
185
185
186
186
186

12. HHVM and Hack. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187


HHVM
PHP at Facebook
HHVM and Zend Engine Parity
Is HHVM Right for Me?
Install
Configure
Extensions
Monitor HHVM with Supervisord
HHVM, FastCGI, and Nginx

| Table of Contents

187
188
189
190
190
191
192
192
194

The Hack Language


Convert PHP to Hack
What is a Type?
Static Typing
Dynamic Typing
Hack Goes Both Ways
Hack Type Checking
Hack Modes
Hack Syntax
Hack Data Structures
HHVM/Hack vs. PHP
Further Reading

195
196
196
197
198
198
199
200
200
202
203
204

13. Community. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205


Local PUG
Conferences
Mentoring
Stay Up-to-Date
Websites
Mailing Lists
Twitter
Podcasts
Humor

205
205
206
206
206
206
206
206
207

A. Installing PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209


B. Local Development Environments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

Table of Contents

xi

CHAPTER 1

The New PHP

The PHP language is experiencing a renaissance. PHP is transforming into a modern


scripting language with helpful features like namespaces, traits, closures, and a builtin opcode cache. The modern PHP ecosystem is evolving, too. PHP developers rely
less on monolithic frameworks and more on smaller specialized components. The
Composer dependency manager is revolutionizing how we build PHP applications; it
emancipates us from a frameworks walled garden and lets us mix and match intero
perable PHP components best suited for our custom PHP applications. Component
interoperability would not be possible without community standards proposed and
curated by the PHP Framework Interop Group.
Modern PHP is your guide to the new PHP, and it will show you how to build and
deploy amazing PHP applications using community standards, good practices, and
interoperable components.

Past
Before we explore modern PHP, it is important to understand PHPs origin. PHP is
an interpreted server-side scripting language. This means you write PHP code,
upload it to a web server, and execute it with an interpreter. PHP is typically used
with a web server like Apache or nginx to serve dynamic content. However, PHP can
also be used to build powerful command-line applications (just like bash, Ruby,
Python, and so on). Many PHP developers dont realize this and miss out on a really
exciting feature. Not you, though.
You can read the official PHP history at http://php.net/manual/history.php.php. I wont
repeat what has already been said so well by Rasmus Lerdorf (the creator of PHP).
What I will tell you is that PHP has a tumultuous past. PHP began as a collection of
CGI scripts written by Rasmus Lerdorf to track visits to his online resume. Lerdorf

named his set of CGI scripts Personal Home Page Tools. This early incarnation was
completely different from the PHP we know today. Lerdorf s early PHP Tools were
not a scripting language; they were tools that provided rudimentary variables and
automatic form variable interpretation using an HTML embedded syntax.
Between 1994 and 1998, PHP underwent numerous revisions and even received a few
ground-up rewrites. Andi Gutmans and Zeev Suraski, two developers from Tel Aviv,
joined forces with Rasmus Lerdorf to transform PHP from a small collection of CGI
tools into a full-fledged programming language with a more consistent syntax and
basic support for object-oriented programming. They named their final product
PHP 3 and released it in late 1998. The new PHP moniker was a departure from ear
lier names, and it is a recursive acronym for PHP: Hypertext Preprocessor. PHP 3 was
the first version that most resembled the PHP we know today. It provided superior
extensibility to various databases, protocols, and APIs. PHP 3s extensibility attracted
many new developers to the project. By late 1998, PHP 3 was already installed on a
staggering 10% of the worlds web servers.

Present
Today, the PHP language is quickly evolving and is supported by dozens of core team
developers from around the world. Development practices have changed, too. In the
past, it was common practice to write a PHP file, upload it to a production server
with FTP, and hope it worked. This is a terrible development strategy, but it was nec
essary due to a lack of viable local development environments.
Nowadays, we eschew FTP and use version control instead. Version control software
like Git helps maintain an auditable code history that can be branched, forked, and
merged. Local development environments are identical to production servers thanks
to virtualization tools like Vagrant and provisioning tools like Ansible, Chef, and
Puppet. We leverage specialized PHP components with the Composer dependency
manager. Our PHP code adheres to PSRscommunity standards managed by the
PHP Framework Interop Group. We thoroughly test our code with tools like
PHPUnit. We deploy our applications with PHPs FastCGI process manager behind a
web server like nginx. And we increase application performance with an opcode
cache.
Modern PHP encompasses many new practices that may be unfamiliar to those of
you new to PHP, or to those upgrading from older PHP versions. Dont feel over
whelmed. Ill walk through each concept later in this book.
Im also excited that PHP now has an official draft specificationsomething it lacked
until 2014.

Chapter 1: The New PHP

Most mature programming languages have a specification. In lay


mans terms, a specification is a canonical blueprint that defines
what it means to be PHP. This blueprint is used by developers who
create programs that parse, interpret, and execute PHP code. It is
not for developers who create applications and websites with PHP.

Sara Golemon and Facebook announced the first PHP specification draft at OReillys
OSCON conference in 2014. You can read the official announcement on the PHP
internals mailing list, and you can read the PHP specification on GitHub.
An official PHP language specification is becoming more important given the intro
duction of multiple competing PHP engines. The original PHP engine is the Zend
Engine, a PHP interpreter written in C and introduced in PHP 4. The Zend Engine
was created by Rasmus Lerdorf, Andi Gutmans, and Zeev Suraski. Today the Zend
Engine is the Zend companys main contribution to the PHP community. However,
there is now a second major PHP enginethe HipHop Virtual Machine from Face
book. A language specification ensures that both engines maintain a baseline
compatibility.
A PHP engine is a program that parses, interprets, and executes
PHP code (e.g., the Zend Engine or Facebooks HipHop Virtual
Machine). This is not to be confused with PHP, which is a generic
reference to the PHP language.

Future
The Zend Engine is improving at a rapid pace with new features and improved per
formance. I attribute the Zend Engines improvements to its new competition, specifi
cally Facebooks HipHop Virtual Machine and Hack programming language.
Hack is a new programming language built on top of PHP. It introduces static typing,
new data structures, and additional interfaces while maintaining backward compati
bility with existing dynamically typed PHP code. Hack is targeted at developers who
appreciate PHPs rapid development characteristics but need the predictability and
stability from static typing.
Well discuss dynamic versus static typing later in this book. The
difference between the two is when PHP types are checked.
Dynamic types are checked at runtime, whereas static types are
checked at compile time. Jump ahead to Chapter 12 for more
information.

Future

The HipHop Virtual Machine (HHVM) is a PHP and Hack interpreter that uses a just
in time (JIT) compiler to improve application performance and reduce memory
usage.
I dont foresee Hack and HHVM replacing the Zend Engine, but Facebooks new con
tributions are creating a giant splash in the PHP community. Increasing competition
has prompted the Zend Engine core team to announce PHP 7, an optimized Zend
Engine said to be on par with HHVM. Well discuss these developments further in
Chapter 12.
Its an exciting time to be a PHP programmer. The PHP community has never been
this energized, fun, and innovative. I hope this book helps you firmly embrace
modern PHP practices. There are a ton of new things to learn, and many more things
on the horizon. Consider this your roadmap. Now lets get started.

Chapter 1: The New PHP

Want to read more?


You can buy this book at oreilly.com
in print and ebook format.
Buy 2 books, get the 3rd FREE!
Use discount code: OPC10
All orders over $29.95 qualify for free shipping within the US.

Its also available at your favorite book retailer,


including the iBookstore, the Android Marketplace,
and Amazon.com.

Spreading the knowledge of innovators

oreilly.com

Anda mungkin juga menyukai