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
Ed Finkler
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
Modern PHP
PHP
CAN $34.99
ISBN: 978-1-491-90501-2
Josh Lockhart
Modern PHP
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
Ed Finkler
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
Modern PHP
PHP
CAN $34.99
ISBN: 978-1-491-90501-2
Josh Lockhart
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.
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.
First Edition
First Release
978-1-491-90501-2
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Part I.
Language Features
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
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
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
Part III.
105
106
106
109
110
112
115
115
118
119
121
123
124
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
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
181
181
182
182
183
183
183
184
184
185
185
185
186
186
186
| Table of Contents
187
188
189
190
190
191
192
192
194
195
196
196
197
198
198
199
200
200
202
203
204
205
205
206
206
206
206
206
206
207
Table of Contents
xi
CHAPTER 1
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.
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.
oreilly.com