31,19 €
This book will get you started with the latest benchmarking, profiling and monitoring tools for PHP, MySQL and JavaScript using Docker-based technologies. From optimizing PHP 7 code to learning asynchronous programming, from implementing Modern SQL solutions to discovering Functional JavaScript techniques, this book covers all the latest developments in Faster Web technologies. You will not only learn to determine the best optimization strategies, but also how to implement them.
Along the way, you will learn how to profile your PHP scripts with Blackfire.io, monitor your Web applications, measure database performance, optimize SQL queries, explore Functional JavaScript, boost Web server performance in general and optimize applications when there is nothing left to optimize by going beyond performance.
After reading this book, you will know how to boost the performance of any Web application and make it part of what has come to be known as the Faster Web.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 217
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor:Amarabha BanerjeeAcquisition Editor:Shweta PantContent Development Editor:Mohammed Yusuf ImaratwaleTechnical Editor:Akhil NairCopy Editor:Safis EditingProject Coordinator:Hardik BhindeProofreader:Safis EditingIndexer:Pratik ShirodkarGraphics:Jason MonteiroProduction Coordinator:Aparna Bhagat
First published: June 2018
Production reference: 1060618
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-221-1
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
At first glance, my initial instinct was to wonder, "why am I reading yet another book on web development?" After all, I've been in the business for so long that I've learned to say, when asked how many years of experience, over 30. What more is there to learn, right? Wrong! First of all, I'm sure deep down in your gut you'll agree that no matter how long you've been in the business, there is always something new to be learned. This is where our friend Andrew Caya comes in.
Andrew is and has been my best student. He's the only one to have attended all the courses I teach for Zend, and also to have purchased all the books and videos I've done for O'Reilly and Packt. Okay, Okay, I can almost hear you muttering to yourself that maybe the guy's crazy, has no control over his spending habits. Well not to worry: his wife has things firmly under control, and his credit cards are currently under house arrest.
So ... Whatabout Andrew? Asidefrom the fact that he not only has a deep understanding of new and existing technologies, he's thorough and tries things out, which is a refreshing departure from many authors who "talk the talk," but do not "walk the walk."
What deeply impressed me about this book, however, and made me realize that it contains essential information for any web developer, no matterhowexperienced, is how Andrew has taken a deep dive not only into new technologies, but very cleverly brought to light aspects of the existing technologies as well.After reading just the first few chapters,I learned things about PHP andbenchmarkingthat I did not realize existed, even having usedsuchtools since their inception.Another example is found in his last chapter,Beyond Performance.Here,Andrew offers masterful insights such as pointing out that the traditional way of viewing performance itself might be an issue, which then leads into a discussion of UI design and user perception.
In this book, Andrew presents the concepts clearly and concisely. He also shows you how to install, configure, and then put to use the various toolsand techniqueswhich, combined, will result in better web performance, that is,the Faster Web.There are plenty of screenshotswherethe various controls, settings, and expected outcomes are meticulously highlighted.I won't bore you with the extensive list oftechnologies,tools,and techniquesAndrew covers, but let me tell you that there's some really exciting stuffherethat will ultimately put you in charge of your website and its development.
Be honest with yourself: do you experience a pang of dread whenever the phone rings, hoping against hope that it's not another customer complaint? Do you find yourself running ragged chasing down bugs? Are you really looking forward to spending yet another weekend at the office eating cold pizza? Andrew's book will turn your life around and "put you back in the driver's seat," as the saying goes. If you apply the concepts and use the tools he describes, you might even start enjoying your job and be able to use all the unused paid leave you've accumulated. Treat yourself to this book and enjoy your day in the sun!
Doug Bierer
unlikelysource.com
P.S. If you're like me and like to poke fun at the hard-core "Test Driven Development" nerds, have a look at Andrew's chapter entitled Javascript and "Danger-Driven Development".
Andrew Caya started programming computers in GW-BASIC and QBASIC in the early 90s. Before becoming a PHP developer almost 10 years ago, he did some software development in C, C++, and Perl. He is now a Zend Certified PHP Engineer and a Zend Certified Architect. He is also the creator of Linux for PHP, the lead developer of a popular Joomla extension and a contributor to many open source projects.
He is currently CEO, CTO and Founder of Foreach Code Factory, an instructor at Concordia University, an author and a technical reviewer for Packt Publishing, and a loving husband and father.
Federico Kereki is a Uruguayan Systems Engineer, with a Masters Degree in Education, and over 30 years’ experience as a consultant, developer, professor, and writer.
He is a Subject Matter Expert at Globant, and he has taught at Universidad de la República, Universidad ORT, and Universidad de la Empresa.
He has written several articles for magazines and web sites, a pair of booklets on computer security, and two books: Essential GWT and Mastering JavaScript Functional Programming. He's currently writing a new book on JavaScript development for Packt Publishing.
Jakub Zalas is an independent software consultant, architect and trainer, who helps teams to deliver software that survives change. Being focused on quality, Jakub promotes agile development practices, like test driven development. In his spare time, he speaks at conferences and contributes to open source.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Mastering The Faster Web with PHP, MySQL, and JavaScript
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Foreword
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Faster Web – Getting Started
What is the Faster Web?
The Faster Web and performance
Measuring the Faster Web
Before Measuring
Benchmark testing and profiling
Practical prerequisites
Understanding Apache Bench (AB)
Understanding Siege
Installing and configuring useful tools
Profiling PHP – xdebug Installation and Configuration
SQL – Speed Testing
JavaScript – Developer Tools
Summary
References
Continuous Profiling and Monitoring
What is Blackfire.io?
Installing and configuring Blackfire.io
Profiling manually with Blackfire.io
Performance testing with Blackfire.io
Monitoring performance with the TICK Stack
Summary
References
Harnessing the Power of PHP 7 Data Structures and Functions
PHP 7 optimizations
Strict typing
Immutable and packed arrays
Memory allocation of integers and floats
String interpolation and concatenation
Parameter references
Identifying more possible optimizations
Functional programming and memoization
Summary
Reference
Envisioning the Future with Asynchronous PHP
Asynchronous non-blocking I/O calls
Multithreading with pthreads
Using the ReactPHP library
Summary
Measuring and Optimizing Database Performance
SQL query performance
The structure of indexes
The execution plan
Basic query optimization
The performance schema and advanced query optimization
Advanced benchmarking tools
DBT2
SysBench
Summary
Querying a Modern SQL Database Efficiently
Modern SQL
Definition
WITH and WITH RECURSIVE
CASE
OVER and PARTITION BY
OVER AND ORDER BY
GROUPING SETS
JSON clauses and functions
FILTER
LATERAL queries
Summary
JavaScript and Danger-Driven Development
The global object and local variables
Avoiding global variables
Evaluating local variables
Avoiding bad idioms and keeping an eye on the very bad parts
Bad idioms
Bad constructs – the with statement
Bad constructs – the eval statement
Bad constructs – the try-catch-finally construct
Avoiding inefficient loops
Linters and strict mode
Using the DOM efficiently
Modifying the document tree
Updating an invisible element
Making style changes
Searching for nodes
Inspecting a large number of nodes
Managing references from one document to another
Caching DOM values
Structuring and loading a JavaScript application
Minimizing costly operations
Cleaning up, minifying, and compressing resources
Loading page resources
Caching page resources
Summary
Functional JavaScript
Simplifying functions
Functional programming principles
Functions as first-class citizens
Dealing with side effects
Immutability
Functional programming techniques
Map
Filter
Reduce
Tail-call optimization
What is TCO?
How TCO works
Recognizing tail-calls
More upcoming JavaScript features
Async functions
Async generators and for-await-of loops
Pipeline operator
Partial application
Summary
Boosting a Web Server's Performance
MOD_SPDY and HTTP/2
Multiplexed and prioritized streams
Server pushing
Header compression
HTTP/2
PHP-FPM and OPCache
PHP-FPM
Zend OPcache
ESI and Varnish Cache
Edge Side Includes (ESI)
Varnish Cache
Client-side caching
Browser caching
Content Delivery Networks (CDNs)
Other Faster Web tools
Summary
References
Going Beyond Performance
Clocked and perceived time
Speed perception
Reasonable delay and response times
UI design principles and patterns
"Beyond Performance" tools
Summary
References
Other Books You May Enjoy
Leave a review - let other readers know what you think
The Faster Web can be defined as a series of qualities to be developed in all spheres of web technology in order to speed up any transaction between a client and a server. It also includes the principles behind UI design that can influence a user's perception of speed. Thus, understanding the Faster Web involves understanding the notions of performance, efficiency and perceived performance, and discovering most of the new underlying web technologies that make up what the internet has become today.
Any web developer, system administrator or web enthusiast who wishes to understand the Faster Web better. Basic knowledge of Docker container technology is a plus.
Chapter 1, Faster Web – Getting Started, defines what is the Faster Web by trying to better understand the formal aspects of it and sets out to understand how to measure performance and determine if a website or Web application is part of the Faster Web or not.
Chapter 2, Continuous Profiling and Monitoring, aims to help the reader learn how to install and configure profiling and monitoring tools that will help them easily optimize PHP code in a continuous integration (CI) and a continuous deployment (CD) environment.
Chapter 3, Harnessing the Power of PHP 7 Data Structures and Functions, gets the reader to learn how to harness PHP 7's performance boosts through most of its key optimizations. It also helps them explore how better understanding data structures and data types, and using simplified functions can help a PHP application's global performance along its critical execution path. In addition, it covers how it is best to avoid using inefficient structures, like most dynamic ones, in our PHP code, and how some functional techniques can be of immediate help when optimizing PHP code.
Chapter 4, Envisioning the Future with Asynchronous PHP, outlines how to cope with input and output (I/O) poor latency by learning about generators and asynchronous non-blocking code, multithreading with the POSIX Threads (pthreads) library and multitasking with the ReactPHP library.
Chapter 5, Measuring and Optimizing Database Performance, shows how to measure database performance, ranging from simple measurement techniques to advanced benchmarking tools.
Chapter 6, Querying Efficiently a Modern SQL Database, explains how to use Modern SQL techniques in order to optimize complex SQL queries.
Chapter 7, JavaScript and Danger-Driven Development, covers a few of JavaScript's best and worst parts, especially those that pertain to code efficiency and overall performance, and how a developer should always write safe, reliable and highly efficient JavaScript code, mostly by avoiding “danger-driven development”.
Chapter 8, Functional JavaScript, features how JavaScript is becoming more and more a functional language and how this programming paradigm will be a vector for performance in the near future by taking a quick look at upcoming language features that will help improve performance of JavaScript applications.
Chapter 9, Boosting a Web Server’s Performance, looks at what the HTTP/2 protocol is all about and how the SPDY project made it possible, how PHP-FPM and OPcache can help you boost the performance of your PHP scripts, how to use ESI technology by setting up a Varnish Cache server, how to use client-side caching and how other Faster Web tools can help you boost a web server's overall performance.
Chapter 10, Going Beyond Performance, shows how, when everything seems to have been fully optimized, we can still go beyond performance by better understanding the principles behind UI design when it comes to the perception of performance.
In order to run the source code included in this book, we recommend that you start by installing Docker on your computer (https://docs.docker.com/engine/installation/). Docker is a software container platform that allows you to easily connect to your computer’s devices in an isolated and sophisticated chroot-like environment. Unlike virtual machines, containers do not come bundled with full operating systems, but only come with the required binaries in order to run some software. You can install Docker on Windows, Mac, or Linux. It should be noted, however, that some features, such as full-featured networking, are still not available when running Docker on macOS (https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds).
The main Docker image that we will be using throughout this book is Linux for PHP 8.1 (https://linuxforphp.net/) with a non thread-safe version of PHP 7.1.16 and MariaDB (MySQL) 10.2.8 (asclinux/linuxforphp-8.1:7.1.16-nts). To start the main container, enter the following command:
# docker run --rm -it \
> -v ${PWD}/:/srv/fasterweb \
> -p 8181:80 \
> asclinux/linuxforphp-8.1:7.1.16-nts \
> /bin/bash
If you prefer using multithreading technologies while optimizing your code, you can do so by running a thread-safe version of Linux for PHP (asclinux/linuxforphp-8.1:7.0.29-zts).
Moreover, you should docker commit any changes you make to the container and create new images of your container that you can docker run at a later time. If you are not familiar with the Docker command line and its run command, find the documentation at https://docs.docker.com/engine/reference/run/.
Finally, the three following commands must be run inside the Linux for PHP container whenever you start an original Linux for PHP image and wish to start working with most of the code examples contained in this book:
# /etc/init.d/mysql start
# /etc/init.d/php-fpm start
# /etc/init.d/httpd start
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
Select the
SUPPORT
tab
Click on
Code Downloads & Errata
Enter the name of the book in the
Search
box and follow the onscreen instructions
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Mastering-the-Faster-Web-with-PHP-MySQL-and-JavaScript. In case there's an update to the code, it will be updated on the existing GitHub repository.
All the code examples given in this book can be found, within the code repository, in a folder named according to the chapter's number. Thus, it is expected that you change your working directory at the beginning of each chapter in order to run the code examples given within. Thus, for chapter 1, you are expected to enter, on the container's CLI, the following commands:
# mv /srv/www /srv/www.OLD# ln -s /srv/fasterweb/chapter_1 /srv/www
And, for the next chapter, you are expected to enter these commands:
# rm /srv/www# ln -s /srv/fasterweb/chapter_2 /srv/www
And, so on for the following chapters.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
The Faster Web is an expression that has been around for a few years now and has been used to designate many different aspects of web performance. In this book, we will take a closer look at what it is. Why is it important? Is it the same thing as performance? How do we measure it? When should we start thinking about it when developing a new project? What are the underlying technologies and how do we harness the power of these technologies in order to make our web projects part of the Faster Web?
In this first chapter, we will start by defining what the Faster Web is and try to better understand the formal aspects of it.
Also, throughout the entire book, we will provide many code examples that will allow us to better understand the concepts behind the Faster Web. We will take the time to look back at its origins, assess its current developments, and look forward to the future in order to understand its next important milestone.
For now, we will start with the installation of benchmarking and profiling tools inside a Docker container in order to learn how to use them. Also, we will take the time to understand how to measure performance and determine if a website or web application is part of the Faster Web or not.
Therefore, this chapter will cover the following points:
Understanding what the Faster Web is and why it is important
Learning to distinguish between the Faster Web and performance
Knowing how to measure the Faster Web
Installing, configuring, and using benchmark testing and profiling tools
In 2009, Google announced its intentions to make the web faster[1] and launched a corresponding initiative by which the web community was invited to think of ways of making the internet go faster. It was stated that "people prefer faster, more responsive apps" and that this was the main reason behind Google's initiative. The announcement also included a list of many challenges identified by Google as being the first order of business of this initiative. The main ones were:
Updating aging protocols
Fixing JavaScript's lack of performance
Finding new measurement, diagnostics and optimization tools
Providing more access to broadband installations across the world
The Faster Web can be defined as a series of qualities to be developed in all spheres of web technology in order to speed up any transaction between a client and a server.
But how important is speed? It is important enough for Google to have discovered, in 2010, that any slowdown had a direct impact on a company's website traffic and ad revenue. In fact, Google successfully established a statistical correlation between traffic and ad revenue, and the number of results and the time it takes to obtain them. The end result of their research was that it is possible to observe a decrease of the order of 20% in traffic and add revenue when obtaining more results in 0.9 seconds versus fewer results on a page in only 0.4 seconds.
