Book Image

PHP Reactive Programming

By : Martin Sikora
Book Image

PHP Reactive Programming

By: Martin Sikora

Overview of this book

Reactive Programming helps us write code that is concise, clear, and readable. Combining the power of reactive programming and PHP, one of the most widely used languages, will enable you to create web applications more pragmatically. PHP Reactive Programming will teach you the benefits of reactive programming via real-world examples with a hands-on approach. You will create multiple projects showing RxPHP in action alone and in combination with other libraries. The book starts with a brief introduction to reactive programming, clearly explaining the importance of building reactive applications. You will use the RxPHP library, built a reddit CLI using it, and also re-implement the Symfony3 Event Dispatcher with RxPHP. You will learn how to test your RxPHP code by writing unit tests. Moving on to more interesting aspects, you will implement a web socket backend by developing a browser game. You will learn to implement quite complex reactive systems while avoiding pitfalls such as circular dependencies by moving the RxJS logic from the frontend to the backend. The book will then focus on writing extendable RxPHP code by developing a code testing tool and also cover Using RxPHP on both the server and client side of the application. With a concluding chapter on reactive programming practices in other languages, this book will serve as a complete guide for you to start writing reactive applications in PHP.
Table of Contents (18 chapters)
PHP Reactive Programming
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Preface

Reactive programming has gained distinct popularity in recent years. This is partly thanks to JavaScript web frameworks such as Angular2 or React, but also because of the increasing popularity of functional and asynchronous programming in languages that support multiple programming paradigms, such as JavaScript, Java, Python, or PHP.

Nowadays, reactive programming is closely associated with Reactive Extensions (also called ReactiveX or just Rx); the most popular library to leverage reactive programming. Notably, RxJS 5, the JavaScript implementation of Rx, is very likely to be the first encounter with reactive programming for many developers. In this book, we will mostly focus on using the PHP port of Rx, called RxPHP (https://github.com/ReactiveX/RxPHP).

Asynchronous programming is not what PHP developers typically deal with. In fact, it’s kind of an uncharted territory because there aren’t many resources available on this topic in PHP. Since reactive programming goes hand in hand with asynchronous programming, we’ll work a lot with event loops, blocking and non-blocking code, subprocesses, threads, and IPC.

Our primary intention, however, will be learning Reactive Extensions and reactive programming with RxPHP. This book includes both RxPHP 1 and RxPHP 2. All examples are written for RxPHP 1 because the API is almost the same, and at the time of writing this book, RxPHP 2 is still in development. Also, RxPHP 1 requires just PHP 5.6+, while RxPHP 2 requires PHP 7+. Nonetheless, we’ll properly emphasize and explain whenever the APIs of RxPHP 1 and RxPHP 2 differ.

What this book covers

Chapter 1, Introduction to Reactive Programming, explains definitions of typical programming paradigms such as imperative, asynchronous, functional, parallel, and reactive programming. We’ll see what are the prerequisites to use functional programming in PHP and how all this is related to Reactive Extensions. At the end, we’ll introduce the RxPHP library as a tool of choice for this entire book.

Chapter 2, Reactive Programming with RxPHP, presents the basic concepts and common terminology used in reactive programming with RxPHP. It introduces Observables, observers, operators, Subjects, and disposables as the building blocks of any Rx application.

Chapter 3, Writing a Reddit Reader with RxPHP, builds on the knowledge from the previous chapter to write a Reddit reader application internally based on RxPHP. This will require downloading data via cURL and handling user input, and comparing the difference between blocking and non-blocking code in PHP in relation to RxPHP. We’ll also have a sneak peak into using event loops in PHP.

Chapter 4, Reactive versus a Typical Event-Driven Approach, shows that in order to use Rx in practice, we need to know how can we combine RxPHP code with some already existing code that isn’t based on Rx. For this reason, we’ll take the Event Dispatcher component that comes with the Symfony3 framework and extend it with Rx functionality.

Chapter 5, Testing RxPHP Code, covers testing, which is a crucial part of every development process. Apart from PHPUnit, we’ll also use the special testing classes that come with RxPHP out of the box. We’ll also take a look at testing asynchronous code in general and what caveats we need to be aware of.

Chapter 6, PHP Streams API and Higher-Order Observables, introduces the PHP Streams API and event loops. These two concepts are tightly coupled in RxPHP and we’ll learn why and how. We’ll talk about the issues we can encounter when using multiple event loops in the same application and how the PHP community is trying to solve them. We’ll also introduce the concept of higher-order Observables as a more advanced functionality of Rx.

Chapter 7, Implementing Socket IPC and WebSocket Server/Client, demonstrates how in order to write a more complicated asynchronous application, we’ll build a chat manager, server, and client as three separate processes that communicate with each other via Unix sockets and WebSockets. We’ll also use in practice the higher-order Observables from the previous chapter.

Chapter 8, Multicasting in RxPHP and PHP7 pthreads Extension, introduces us to the concept of multicasting in Rx and all the components that RxPHP provides for this purpose. We’ll also start using the pthreads extension for PHP7. This will let us run our code in parallel in multiple threads.

Chapter 9, Multithreaded and Distributed Computing with pthreads and Gearman, wraps the knowledge of pthreads from the previous chapter into reusable components that can be used together with RxPHP. We also introduce the Gearman framework as a way to distribute work among multiple processes. In the end, we’ll compare the pros and cons of using multiple threads and processes to run tasks in parallel.

Chapter 10, Using Advanced Operators and Techniques in RxPHP, will focus on not-so-common principles in Rx. These are mostly advanced operators for very specific tasks, but also implementation details of RxPHP components and their behavior in specific use cases that we should be aware of.

Appendix, Reusing RxPP Techniques in RxJS, demonstrates with practical examples how to deal with typical use cases where either RxPHP or RxJS come in handy. We'll see how asynchronous programming is used in a JavaScript environment and compare it to PHP. This final chapter also goes into more detail about what RxJS 5 is and how it differs from RxPHP.

What you need for this book

The main prerequisites for most of this book are a PHP 5.6+ interpreter and any text editor.

We’ll use the Composer (https://getcomposer.org/) tool to install all external dependencies in our examples. Some basic knowledge of Composer and PHPUnit is helpful but not absolutely necessary.

In later chapters, we’ll also use the pthreads PHP extension, which requires PHP 7 or above and the Gearman job server; both should be available for all platforms.

Also, some basic knowledge of the Unix environment (sockets, processes, signals, and so on) is helpful.

Who this book is for

This book is intended for intermediate developers with at least average knowledge of PHP who want to learn about asynchronous and reactive programming in PHP and Reactive Extensions in particular.

Apart from the RxPHP library, this book is framework agnostic, so you don’t need knowledge of any web framework.

All the topics regarding RxPHP are generally applicable to any Rx implementation, so switching from RxPHP to RxJS, for example, will be very easy.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Every time we write an Observable, we'll extend the base Rx\Observable class."

A block of code is set as follows:

Rx\Observable::just('{"value":42}')
    ->lift(function() {
        return new JSONDecodeOperator();
    })
    ->subscribe(new DebugSubject());

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

use Rx\Observable\IntervalObservable;
class RedditCommand extends Command {
  /** @var \Rx\Subject\Subject */
  private $subject;
  private $interval;

Any command-line input or output is written as follows:

$ sleep.php proc1 3

proc1: 1

proc1: 2

proc1: 3

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "PHP has to be compiled with the Thread Safety option enabled."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

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 at https://github.com/PacktPublishing/PHP-Reactive-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.