Docsity

Modern PHP Manav Kumar Sanand, Study notes of Computer Science

Partial preview of the text

Download Modern PHP Manav Kumar Sanand and more Study notes Computer Science in PDF only on Docsity!

Modern PHP

New Features and Good Practices

Josh Lockhart

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-

[LSI]

For Laurel

What You Need to Know About This Book

Before we get started, I want to set a few expectations. First, it is impossible for me to cover every way to use PHP. There isn’t enough time. Instead, I will show you how I use PHP. Yes, this is an opinionated approach, but I use the very same practices and standards adopted by many other PHP developers. What you take away from our brief conversation will be immediately applicable in your own projects.

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.

How This Book Is Organized

Part I demonstrates new PHP features like namespaces, generators, and traits. It introduces you to the modern PHP language, and it exposes you to features you may not have known about until now.

Part II explores good practices that you should implement in your PHP applications. Have you heard the term PSR , but you’re not entirely sure what it is or how to use it? Do you want to learn how to sanitize user input and use safe database queries? This chapter is for you.

Part III is more technical than the first two parts. It demonstrates how to deploy, tune, test, and profile PHP applications. We dive into deployment strategies with Capistrano. We talk about testing tools like PHPUnit and Travis CI. And we explore how to tune PHP so it performs as well as possible for your application.

Appendix A provides step-by-step instructions for installing and configuring PHP-FPM on your machine.

Appendix B explains how to build a local development environment that closely matches your production server. We explore Vagrant, Puppet, Chef, and alternative tools to help you get started quickly.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/codeguy/modern-php.

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “ Modern PHP by Josh Lockhart (O’Reilly). Copyright 2015 Josh Lockhart, 978-1-491-90501-2.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected].

Safari® Books Online

Note

Safari Books Online is an on-demand digital library that delivers 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 creative 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 Kaufmann, 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.

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 (@allyatoreilly). 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 personality on the /dev/hell podcast, and his commendable Open Sourcing Mental Illness 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 encouragement. 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 beginning 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.

Part I. Language Features

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 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 earlier 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 necessary 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 overwhelmed. 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.

Note

Most mature programming languages have a specification. In layman’s 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 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 introduction 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 Facebook. A language specification ensures that both engines maintain a baseline compatibility.

Note

A PHP engine is a program that parses, interprets, and executes PHP code (e.g., the Zend Engine or Facebook’s HipHop Virtual Machine). This is not to be confused with PHP , which is a generic reference to the PHP language.

Chapter 2. Features

The modern PHP language has many exciting new features. Many of these features will be brand new to PHP programmers upgrading from earlier versions, and they’ll be a nice surprise to programmers migrating to PHP from another language. These new features make the PHP language a powerful platform and provide a pleasant experience for building web applications and command-line tools.

Some of these features aren’t essential, but they still make our lives easier. Some features, however, are essential. Namespaces, for example, are a cornerstone of modern PHP standards and enable development practices that modern PHP developers take for granted (e.g., autoloading). I’ll introduce each new feature, explain why it is useful, and show you how to implement it in your own projects.

Tip

I encourage you to follow along on your own computer. You can find all of the text’s code examples in this book’s companion GitHub repository.

Namespaces

If there is one modern PHP feature I want you to know, it is namespaces. Introduced in PHP 5.3.0, namespaces are an important tool that organizes PHP code into a virtual hierarchy, comparable to your operating system’s filesystem directory structure. Each modern PHP component and framework organizes its code beneath its own globally unique vendor namespace so that it does not conflict with, or lay claim to, common class names used by other vendors.

Note

Don’t you hate it when you walk into a coffee shop and this one obnoxious person has a mess of books, cables, and whatnot spread across several tables? Not to mention he’s sitting next to, but not using, the only available power outlet. He’s wasting valuable space that could otherwise be useful to you. Figuratively speaking, this person is not using namespaces. Don’t be this person.

Let’s see how a real-world PHP component uses namespaces. The Symfony Framework’s own symfony/httpfoundation is a popular PHP component that manages HTTP requests and responses. More important, the symfony/httpfoundation component uses common PHP class names like Request, Response, and Cookie. I guarantee you there are many other PHP components that use these same class names. How can we use the symfony/httpfoundation PHP component if other PHP code uses the same class names? We can safely use the symfony/httpfoundation component precisely because its code is sandboxed beneath the unique Symfony vendor namespace. Visit the symfony/httpfoundation component on GitHub and navigate to the Response.php file. It looks like Figure 2-1.

Figure 2-1. GitHub symfony/httpfoundation screenshot

Look closely at line 12. It contains this code: