30,96 €
Explore tools, techniques, and practices to remove performance bottlenecks and enhance the stability of your Laravel and PHP web applications
Key Features
Book Description
Laravel Octane is a very powerful component in the Laravel ecosystem that can help you achieve remarkable app performance. With Laravel Octane, you will find tools (queues, cache, and tables) that facilitate a new asynchronous approach for improving application performance.
This book highlights how Laravel Octane works, what steps to take in designing an application from the start, what tools you have at your disposal, and how to set up production environments. It provides complete coverage of the strategies, tools, and best practices to make your apps scalable and performant. This is especially important as optimization is usually the overlooked part in the application development lifecycle. You will explore the asynchronous approach in Laravel and be able to release high-performing applications that have a positive impact on the end-user experience.
By the end of this book, you will find yourself designing, developing, and releasing high-performance applications.
What you will learn
Who this book is for
The book is for existing Laravel developers who want to improve their software architecture, from a basic or standard architecture to a more scalable and performant one. Basic knowledge of Laravel fundamentals is required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 212
Veröffentlichungsjahr: 2023
Learn to fine-tune and optimize PHP and Laravel apps using Octane and an asynchronous approach
Roberto Butti
BIRMINGHAM—MUMBAI
Copyright © 2022 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.
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Bhavya Rao
Senior Editor: Mark D’Souza
Senior Content Development Editor: Debolina Acharyya
Technical Editor: Saurabh Kadave
Copy Editor: Safis Editing
Project Coordinator: Sonam Pandey
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Prashant Ghare
Marketing Coordinator: Anamika Singh
First published: December 2022
Production reference: 1081222
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80181-940-4
www.packt.com
To my family, for supporting and inspiring me.
– Roberto Butti
Roberto Butti has been working in web development since 2000. He has worked for different markets and companies using several languages/frameworks in both server- and client-side web development.
Today, he is focused on web architecture with Laravel on the server side and various reactive Javascript frameworks, such as Vue and Svelte, on the client side.
Always passionate about performant and scalable architectures, he has found – in Laravel Octane and, more generally, in Open Swoole – an enabling tool for projects where concurrency, real-time communication, and performance are crucial.
Fabio Ivona is an Italian software engineer, proud husband, and father of three sweet children, working as a full-stack developer with PHP and JS since 2005. He came across Laravel (v4) in 2013 and immediately fell in love with it, exploring all its cool features every day.
His workstation is an Ubuntu Linux laptop, and his everyday toolbox consists of Laravel, Livewire/Inertia, Tailwind, Alpine.js, Vite, Angular, and React, as well as Docker and Kubernetes.
He’s currently the founder/CTO at def.studio, a web development company. He’s a member of the Pest PHP core team and regularly contributes to open source projects on his own and fellow developers’ repositories.
Andrea Marco Sartori is an Italian software engineer who lives in Australia. He has over 16 years of experience as a web developer and over 9 years of experience with the Laravel framework.
He has worked on a number of projects for several international organizations, from start-ups to large companies, including Yahoo!
He is an active member of the Laravel community and likes to contribute to the Laravel ecosystem by sending pull requests to the core or by creating free packages that are downloaded hundreds of thousands of times.
This book provides a 360-degree overview of what it takes to design and build a performant application with Laravel Octane, why you should, and how to do it. This book also covers the different tools used by Laravel Octane, such as Swoole and RoadRunner, and lists and explains the various features and differentiating elements. But the most important thing is that it will enable you to understand why and when to use Swoole or RoadRunner.
This book is for those Laravel developers who already know the fundamentals of the framework, such as routing mechanisms, controllers, services, and models. It is meant for those developers who would like to design their applications in a more scalable way and make them more performant.
Chapter 1, Understanding the Laravel Web Application Architecture, is where Laravel Octane introduces new features, but more importantly a new way of thinking about how to design high-performance Laravel applications.
Chapter 2, Configuring the RoadRunner Application Server, shows us a scenario where Laravel Octane is based on the RoadRunner application server. RoadRunner is a very fast and effective application server that is easy to install. Because of its simplicity, it allows the user to approach Laravel Octane easily and straightforwardly.
Chapter 3, Configuring the Swoole Application Server, shows us a scenario where Laravel Octane is based on the Swoole application server. Running Swoole as an application server allows the developer to use some advanced features, such as managing multiple workers and concurrent tasks, bootstrapping the application more efficiently, fast caching, and sharing data among workers. Laravel Octane uses Swoole, so it is important to have clear ideas about the opportunities that arise from using these application servers.
Chapter 4, Building a Laravel Octane Application, teaches us how to build an application with practical examples using features provided by the Swoole application server.
Chapter 5, Reducing Latency and Managing Data with an Asynchronous Approach, teaches us that, once the developer has sped up the bootstrapping of the framework and has removed bottlenecks on the request side, they have to reduce latency in other parts of the application. The chapter introduces useful techniques to reduce latency in executing tasks and managing data.
Chapter 6,Using Queues to Apply the Asynchronous Approach in Your Application, teaches us that in addition to the various tools available with application servers, we can add extra components to our application architecture. One of the main tools to go alongside application servers for greater scalability of a solution is queuing mechanisms. This chapter shows what the benefits are of adding a queuing mechanism to our application.
Chapter 7, Configuring the Laravel Octane Application for the Production Environment, discusses going to production and covers environment-specific configurations, deploying an application to an application server, and fine-tuning the configuration of nginx as a reverse proxy for Swoole.
You will need PHP 8.0 or above installed on your computer. All code examples have been tested using PHP 8.1 on macOS and GNU/Linux.
Software/hardware covered in the book
Operating system requirements
Laravel 9
Windows, macOS, or Linux
PHP 8+
If you don’t want to have PHP installed on your local machine and you are familiar with the Docker setup, you could use the Docker images provided by Laravel Sail. The book explains both local installation and installation via Docker images for the setup of the application servers and the modules (Swoole/OpenSwoole).
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/High-Performance-with-Laravel-Octane. If there’s an update to the code, it will be updated in the GitHub repository.
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/ZTNyn
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “From the Symfony world, Laravel includes packages such as Symfony/routing to manage routing, and http-foundation and http-kernel to manage HTTP communication.”
A block of code is set as follows:
"nyholm/psr7": "^1.5", "spiral/roadrunner": "v2.0"When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
command=/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --server=swoole --host=0.0.0.0 --port=80 --watchAny command-line input or output is written as follows:
npm install --save-dev chokidarBold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Once everything is fine, you will see Table created! on your web page. This means that the rows were created in the right way.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
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/support/errata and fill in the form.
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.
Once you’ve read High-Performance Laravel Development with Octane, we’d love to hear your thoughts! Please click here to go straight to the Amazon review pagefor this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781801819404
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyThe objective of this part is to familiarize you with the application server architecture for PHP and show how the application server shares resources across the workers to serve HTTP requests.
This part comprises the following chapters:
Chapter 1, Understanding the Laravel Web Application ArchitectureThis book is for Laravel developers who would like to make or design their Laravel web application in a more scalable way and make it more performant.
This book aims to provide you with knowledge, suggestions, and explanations on how to improve the software architecture of a web application, starting from a typical PHP web application architecture to a more scalable and performant architecture.
It provides a 360-degree overview of what it takes to design and build a performant application with Laravel Octane. We’ll see why Laravel Octane is suitable for designing and building a performant application. The book also covers the different tools used by Laravel Octane, such as Open Swoole and RoadRunner, and lists and describes the various features and differentiating elements. But the most important thing is to enable you to understand why and when to use Open Swoole or RoadRunner.
But before starting, why use Laravel Octane?
Laravel Octane is a tool that allows us to access some functionality and features exposed by the two application servers we just mentioned.
One of the benefits of Laravel Octane is the huge improvement in the response times to HTTP requests by clients such as web browsers. When we develop a Laravel application, we use an important software layer implemented by the framework. This software layer needs time and resources to start. Even if we talk about only a few resources and a short amount of time, this repeated action for each request, especially in a context where there are many requests, can be a problem. Or rather, its optimization could bring enormous benefits.
Laravel Octane, through application servers, does just that: optimizes the process of starting the framework, which typically happens for each individual request. We will see in detail how this is done; essentially, the objects and everything that the framework needs are started and allocated to the start of the application server, and then the instances are made available to the various workers. Workers are the processes that are initiated to serve the requests.
Another reason why it is interesting to evaluate the adoption of Laravel Octane in your Laravel web application is that by using an application server such as Swoole, you can access those features implemented by Swoole.
The functions are, for example, the advanced mechanisms of the cache driver, shared storage for sharing information between the various workers, and the execution of tasks in parallel.
This is a totally new concept to the classic PHP developer who typically does not have an immediate functionality available in the PHP core for the parallelization of processes.
This chapter will introduce you to the Laravel ecosystem and explore what Laravel Octane is.
This chapter aims to introduce you to the application server approach, in which more workers cooperate to manage multiple requests. Understanding the behavior under the hood allows the developer to avoid some mistakes, especially on shared resources (objects and global states) across the worker. This is important because the classical PHP approach is to have one dedicated thread to manage one request.
In this chapter, we will cover the following topics:
Exploring the Laravel ecosystemUnderstanding the request lifecycleGetting to know the application serverIn order to run the code and tools shown in this book, you must have the PHP engine installed on your machine. It is recommended that you have a recent version of PHP installed (at least 8.0, released in November 2020).
Also, in order to easily install additional tools, it is recommended that you have Homebrew installed if you use macOS. In the case of GNU/Linux systems, it will be sufficient to resort to using the package manager of the distribution used, and in the case of Windows systems, the advice is to have a virtual environment, for example, with Docker.
In the current chapter, some commands and source code will be shown, simply to share some concepts. In subsequent chapters, especially the second chapter about RoadRunner and the third chapter about Open Swoole, the installation of each package and tool will be addressed step by step.
There are those who, regardless of their operating system, prefer to maintain a “clean” installation by resorting to using Docker regardless of the host operating system. Where the next chapters deal with the installation of operating system-dependent tools, the different methods will be highlighted depending on the system in use.
The source code and the configuration files of the examples described in the current chapter are available here: https://github.com/PacktPublishing/High-Performance-with-Laravel-Octane/tree/main/octane-ch01
Laravel is a great framework in the PHP ecosystem that helps developers to build web applications quickly and reliably.
It includes, as dependencies, some great tools from the PHP ecosystem, such as Symfony packages, and some other solid and mature packages such as Monolog for logging, Flysystem for accessing files and storage, and CommonMark for managing Markdown format.
From the Symfony world, Laravel includes packages such as Symfony/routing to manage routing, and http-foundation and http-kernel to manage HTTP communication.
All this is just to say that Laravel uses the best parts of the PHP ecosystem, puts them together, and provides tools, helpers, classes, and methods to simplify the usage of all the tools from the developer’s perspective.
In addition, Laravel is more than a framework. Laravel is an ecosystem.
Laravel also provides applications and services that are integrated with the framework.
For example, Laravel provides the following:
Cashier: For integration with Stripe and Paddle for the payment and subscription process.Breeze, Jetstream, Sanctum, and Socialite: For managing authorization, authentication, the social login integration process, and exposing protected APIs.Dusk and Pest: For testing.Echo: For broadcasting events in real time.Envoyer, Forge, and Vapor: For server or serverless management and to manage the deployment process.Mix: For compiling JavaScript and CSS through a webpack configuration fully integrated with the Laravel frontend.Horizon: A web user interface for monitoring queues based on Redis.Nova: An administrator panel builder for Laravel applications.Sail: A local development environment based on Docker.Scout: A full-text search engine, backed by providers such as Algolia, Meilisearch, or simply by the MySQL or PostgreSQL database.Spark: A boilerplate solution for managing billing/subscription in your application.Telescope: UI module for showing debugging and insights.Valet: A macOS-specific bundle of applications configured for running the PHP application. It has dependencies with nginx, PHP, and Dnsmasq.Octane: For improving performance and optimizing resources.In this book, we will analyze the last tool in this list: Laravel Octane.
We will go over the use of other tools within the Laravel ecosystem, such as Sail (for simplifying the installation process of a complete development environment), and Valet (for correctly setting up the local environment to run a web server and PHP). Also, Laravel Octane depends on important software that we will see in-depth throughout the book. Laravel Octane has strong requirements: it requires additional software such as Swoole or RoadRunner.
But one step at a time.
Before we delve into the tools and their configuration, it’s important to understand some basic mechanisms for managing HTTP requests.
HTTP
HTTP is a protocol that defines rules, messages, and methods for fetching resources on the web, such as HTML documents (web pages) and assets. Clients (who require the resource) and servers (who serve the resource) communicate by exchanging messages. The client sends requests, and the server sends responses.
One of the goals of the book is to empower you to improve the performance of your web applications by doing different things, starting with designing the architecture of the application, choosing and using the right tools, writing code, and finally, releasing the application.
The tools we are going to analyze and use will do much of the work, but I think it is important to understand the underlying dynamics to have a good awareness of how the various tools work to enable you to configure, integrate, and use them to the best of their ability.
Before we get deeper into the workings of Laravel Octane, let me take you through how servers typically deal with HTTP requests by explaining the HTTP request lifecycle.
There are a number of components involved in performing the HTTP request. The components are as follows:
Client: This is where the request starts and the response ends (for example, the browser).Network: The requests and responses go through this and it connects the server and the client.Proxy: This is an optional component that could perform some tasks before the request reaches the web server, such as caching, rewriting and/or altering the request, and forwarding the request to the right web server.Web server: This receives the request and is responsible for selecting the correct resource.PHP: The language, or more generally in the case of server-side languages, the language-specific engine that is used and involved. In this case, the PHP interpreter is used. The PHP interpreter can be activated mainly in two ways: as a web server module or as a separate process. In the latter case, a technology called FastCGI Process Manager (FPM) is used. We will see how this mechanism works later in more detail. For now, it is useful to know that the web server somehow invokes the server-side language interpreter. By doing this, our server is able to interpret the language. If the invoked resource is a PHP-type file with the specific PHP syntax, the resource file requested is interpreted by the PHP engine. The output is sent back in the form of a response to the web server, the network, and then the browser.Framework: In the case that the application is written with PHP and a framework is used, as a developer, you can access classes, methods, and helpers to build your application faster.The components are called sequentially in the HTTP request flow. The HTTP request starts from the browser, then goes through the network (optionally passing through via the proxy), until it reaches the web server that invokes the PHP engine and the framework is bootstrapped.
From a performance point of view, if you want to bring some improvement, you have to take some action or implement some solution depending on the elements of this architecture.
For example, on the browser side, you could work on caching assets in the browser or on the optimization of your JavaScript code. On the networking side, one solution could be resource optimization, for example, reducing the weight of assets or introducing architectural elements such as a CDN. In the case of the web server, an effective first-level improvement could be to avoid loading the PHP engine for the static assets (non-PHP files).
All such fine-tuning will be addressed in the final chapters, where we will deal with the configuration and optimization of production elements. Most of the book covers the optimization of the framework. For example, in Chapters 2 and 3, topics such as the use of Octane with tools such as Swoole and RoadRunner, which enable more efficient and effective loading of resources (shared objects and structures), are addressed. Other points of performance improvement on the framework side include the introduction of an asynchronous approach through the use of queuing systems (Chapters 6and 7).
Now that you have an idea of the components involved in an HTTP request, let’s look at the structure of an HTTP request.
To understand in detail what happens in a typical HTTP request, we start by analyzing what is sent from the browser to the server during a request. A request is mainly characterized by methods (GET, POST, PUT, and so on), the URL, and HTTP headers.