Complete Modern PHP New Features and Good Practices 1st Edition Josh Lockhart PDF For All Chapters
Complete Modern PHP New Features and Good Practices 1st Edition Josh Lockhart PDF For All Chapters
Complete Modern PHP New Features and Good Practices 1st Edition Josh Lockhart PDF For All Chapters
com
https://textbookfull.com/product/modern-php-new-
features-and-good-practices-1st-edition-josh-
lockhart/
https://textbookfull.com/product/web-content-management-systems-
features-and-best-practices-first-edition-barker/
textbookfull.com
Arithmetic Lockhart
https://textbookfull.com/product/arithmetic-lockhart/
textbookfull.com
PHP Web Services APIs for the Modern Web 2nd Edition Lorna
Jane Mitchell
https://textbookfull.com/product/php-web-services-apis-for-the-modern-
web-2nd-edition-lorna-jane-mitchell/
textbookfull.com
https://textbookfull.com/product/laparoscopic-colon-surgery-
milestones-education-best-practice-gregory-kouraklis/
textbookfull.com
Lessons from Frankenstorm Investing for Future Power
Disruptions 1st Edition John Licata
https://textbookfull.com/product/lessons-from-frankenstorm-investing-
for-future-power-disruptions-1st-edition-john-licata/
textbookfull.com
https://textbookfull.com/product/rooftop-urban-agriculture-1st-
edition-francesco-orsini/
textbookfull.com
https://textbookfull.com/product/industrial-hygiene-control-of-
airborne-chemical-hazards-second-edition-william-popendorf-author/
textbookfull.com
https://textbookfull.com/product/robert-louis-stevensons-pacific-
impressions-photography-and-travel-writing-1888-1894-carla-manfredi/
textbookfull.com
https://textbookfull.com/product/the-practice-manager-third-edition-
drury/
textbookfull.com
Modern PHP
“For
Modern PHP
PHP is experiencing a renaissance, though it may be difficult to tell with all of years I've struggled
the outdated PHP tutorials online. With this practical guide, you’ll learn how
to recommend a PHP
PHP has become a full-featured, mature language with object-orientation,
namespaces, and a growing collection of reusable component libraries. book that reflected
Author Josh Lockhart—creator of PHP The Right Way, a popular initiative
the current state of
to encourage PHP best practices—reveals these new language features the language and
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
you have a basic understanding of PHP and want to bolster your skills,
this is your book. I can endorse without
Modern
■■ Explore Facebook’s HVVM and Hack language applications has to
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
PHP
need to be aware of to
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.
Lockhart
PHP
Twitter: @oreillymedia NEW FEATURES AND GOOD PRACTICES
facebook.com/oreilly
US $29.99 CAN $34.99
ISBN: 978-1-491-90501-2
Josh Lockhart
Modern PHP
“For
Modern PHP
PHP is experiencing a renaissance, though it may be difficult to tell with all of years I've struggled
the outdated PHP tutorials online. With this practical guide, you’ll learn how
to recommend a PHP
PHP has become a full-featured, mature language with object-orientation,
namespaces, and a growing collection of reusable component libraries. book that reflected
Author Josh Lockhart—creator of PHP The Right Way, a popular initiative
the current state of
to encourage PHP best practices—reveals these new language features the language and
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
you have a basic understanding of PHP and want to bolster your skills,
this is your book. I can endorse without
Modern
■■ Explore Facebook’s HVVM and Hack language applications has to
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
PHP
need to be aware of to
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.
Lockhart
PHP
Twitter: @oreillymedia NEW FEATURES AND GOOD PRACTICES
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].
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
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
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
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
8. Tuning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
The php.ini File 149
Memory 150
Zend OPcache 151
File Uploads 152
Max Execution Time 153
Session Handling 154
Output Buffering 155
Realpath Cache 155
Up Next 155
9. Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Version Control 157
Automate Deployment 157
Make It Simple 158
Make It Predictable 158
Make It Reversible 158
Capistrano 158
How It Works 158
Install 159
Configure 159
Authenticate 161
Prepare the Remote Server 161
Capistrano Hooks 162
Deploy Your Application 163
Roll Back Your Application 163
Further Reading 163
What’s Next 163
Table of Contents | ix
PHPUnit 168
Directory Structure 169
Install PHPUnit 170
Install Xdebug 170
Configure PHPUnit 171
The Whovian Class 172
The WhovianTest Test Case 173
Run Tests 175
Code Coverage 176
Continuous Testing with Travis CI 177
Setup 177
Run 178
Further Reading 178
What’s Next 179
x | Table of Contents
The Hack Language 195
Convert PHP to Hack 196
What is a Type? 196
Static Typing 197
Dynamic Typing 198
Hack Goes Both Ways 198
Hack Type Checking 199
Hack Modes 200
Hack Syntax 200
Hack Data Structures 202
HHVM/Hack vs. PHP 203
Further Reading 204
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Table of Contents | xi
Preface
There are a million PHP tutorials online. Most of these tutorials are outdated and
demonstrate obsolete practices. Unfortunately, these tutorials are still referenced
today thanks to their Google immortality. Outdated information is dangerous to
unaware PHP programmers who unknowingly create slow and insecure PHP applica‐
tions. I recognized this issue in 2013, and it is the primary reason I began PHP The
Right Way, a community initiative to provide PHP programmers easy access to high-
quality and up-to-date information from authoritative members of the PHP
community.
Modern PHP is my next endeavor toward the same goal. This book is not a reference
manual. Nope. This book is a friendly and fun conversation between you and me. I’ll
introduce you to the modern PHP programming language. I’ll show you the latest
PHP techniques that I use every day at work and on my open source projects. And I’ll
help you use the latest coding standards so you can share your PHP components and
libraries with the PHP community.
You’ll hear me say “community” over and over (and over). The PHP community is
friendly and helpful and welcoming—although not without occasional drama. If you
become curious about a specific feature mentioned in this book, reach out to your
local PHP user group with questions. I guarantee you there are nearby PHP develop‐
ers who would love to help you become a better PHP programmer. Your local PHP
user group is an invaluable resource as you continue to improve your PHP skills long
after you finish this book.
xiii
Second, I assume you are familiar with variables, conditionals, loops, and so on; you
don’t have to know PHP, but you should at least bring a basic understanding of these
fundamental programming concepts. You can also bring coffee (I love coffee). I’ll
supply everything else.
Third, I do not assume you are using a specific operating system. However, my code
examples are written for Linux. Bash commands are provided for Ubuntu and
CentOS and may also work on OS X. If you use Windows, I highly recommend you
spin up a Linux virtual machine so you can run the example code in this book.
xiv | Preface
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
Preface | xv
Safari® Books Online
Safari Books Online is an on-demand digital library that deliv‐
ers expert content in both book and video form from the
world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/modern_php.
To comment or ask technical questions about this book, send email to bookques‐
[email protected].
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
xvi | Preface
Acknowledgments
This is my first book. When O’Reilly approached me about writing Modern PHP, I
was equally excited and scared to death. The first thing I did was a Walter Huston
dance; I mean, O’Reilly wanted me to write a book. How cool is that!? Then I asked
myself can I really write that many pages? A book isn’t a quick or small task.
Of course, I immediately said “yes.” I knew I could write Modern PHP because I had
family, friends, coworkers, editors, and reviewers supporting me the entire way. I
want to acknowledge and thank my supporters for their invaluable feedback. Without
them, this book would never have happened.
First, I want to thank my editor at O’Reilly Media—Allyson MacDonald (@allyator‐
eilly). Ally was nice, critical, supportive, and smart. She knew exactly how and when
to gently nudge me in the right direction whenever I got off track. I can’t imagine
working with a better editor.
I also want to thank my technical reviewers—Adam Fairholm (@adamfairholm) and
Ed Finkler (@funkatron). Adam is a brilliant web developer at Newfangled, and he is
perhaps best known for his work on IMVDb—the popular music video database. Ed
is well-known throughout the PHP community for his incredible PHP skills, his per‐
sonality on the /dev/hell podcast, and his commendable Open Sourcing Mental Ill‐
ness campaign. Adam and Ed both pointed out everything dumb, illogical, and
incorrect in my early drafts. This book is far better than anything I could write on my
own thanks to their brutally honest feedback. I am forever indebted to them for their
guidance and wisdom. If any faults or inaccuracies wriggled their way into the final
manuscript, those faults are surely my own.
My coworkers at New Media Campaigns have been a constant source of encourage‐
ment. Joel, Clay, Kris, Alex, Patrick, Ashley, Lenny, Claire, Todd, Pascale, Henry, and
Nathan—I tip my hat to all of you for your kind words of encouragement from begin‐
ning to end.
And most important, I want to thank my family—Laurel, Ethan, Tessa, Charlie, Lisa,
Glenn, and Liz. Thank you for your encouragement, without which I would have
never finished this book. To my lovely wife, Laurel, thank you for your patience.
Thank you for accompanying me to Caribou Coffee for so many late-night writing
sessions. Thank you for letting me abandon you on weekends. Thank you for keeping
me motivated and on schedule. I love you now and forever.
Preface | xvii
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
PART I
Language Features
CHAPTER 1
The New PHP
Past
Before we explore modern PHP, it is important to understand PHP’s 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 don’t 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 won’t
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
1
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 3’s extensibility attracted
many new developers to the project. By late 1998, PHP 3 was already installed on a
staggering 10% of the world’s 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 PSRs—community standards managed by the
PHP Framework Interop Group. We thoroughly test our code with tools like
PHPUnit. We deploy our applications with PHP’s 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. Don’t feel over‐
whelmed. I’ll walk through each concept later in this book.
I’m also excited that PHP now has an official draft specification—something it lacked
until 2014.
Sara Golemon and Facebook announced the first PHP specification draft at O’Reilly’s
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 company’s main contribution to the PHP community. However,
there is now a second major PHP engine—the HipHop Virtual Machine from Face‐
book. A language specification ensures that both engines maintain a baseline
compatibility.
Future
The Zend Engine is improving at a rapid pace with new features and improved per‐
formance. I attribute the Zend Engine’s improvements to its new competition, specifi‐
cally Facebook’s 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 PHP’s rapid development characteristics but need the predictability and
stability from static typing.
We’ll 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 | 3
Random documents with unrelated
content Scribd suggests to you:
If this man had lived long enough, he might have furnished an
instance of hernia of the stomach or of intestine into the
pericardium. The preparation is in the military museum at Chatham,
Class 1, Div. 1, Sect. 7, No. 156.
a, right ventricle;
b, left ditto;
c, right auricle;
d, left ditto;
e, aorta;
f, pulmonary artery;
g, coronary ditto;
h, a portion of the cartilages of the ribs seen on the inside;
i, a portion of the diaphragm;
k, the pericardium.
1, a portion of the pericardium reflected to show abnormal adhesions to the surface of the
heart;
2, aperture of wound through the diaphragm and the pericardium;
3, pendulous slice off the substance of the right ventricle;
4, puckered cicatrix of the wound of the ventricle.