Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
PHP Reactive Programming
PHP Reactive Programming

PHP Reactive Programming: Build fault tolerant and high performing application in PHP based on the reactive architecture

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

PHP Reactive Programming

Chapter 2. Reactive Programming with RxPHP

In this chapter, we're going to have a better look at how we can use PHP's reactive extension library RxPHP. We'll mostly build on what we saw in the previous chapter, but going into greater detail.

In particular, we'll go through the following:

  • Various components of RxPHP that we'll use in this and all further chapters.
  • We'll quickly have a look at how to read and understand the Rx documentation. In particular, we'll have a look at marble diagrams that explain the functionality of Rx operators.
  • List a few basic operators that we'll use throughout the entire book and explain their functionality.
  • Write custom operator that decodes JSON strings into their appropriate array representations while properly handling errors.
  • Implement a simple script that downloads an HTML page via cURL. Then compare the same approach when utilizing RxPHP.
  • How to write a custom Observable for our cURL example.
  • We'll dig into...

Basic principles of Reactive Extensions

Let's have a look at a very simple example of RxPHP, similar to what we did in the previous chapter, and use it to demonstrate some of the basic principles behind Reactive Extensions.

We won't bother with defining an observer right now and will focus only on Observables and operators:

// rxphp_basics_01.php 
use Rx\Observable; 
$fruits = ['apple', 'banana', 'orange', 'raspberry']; 
 
Observable::fromArray($fruits) // Observable 
    ->map(function($value) { // operator 
        return strlen($value); 
    }) 
    ->filter(function($len) { // operator 
        return $len > 5; 
    }) 
    ->subscribe($observer); // observer 

In this example, we have one Observable, two operators and one observer.

An Observable can be chained with operators. In this example, the operators are map() and filter().

Observables have the subscribe() method that is used by observers to start receiving values...

Naming conventions in Reactive Extensions

When talking about Observables, we use terms such as emit/send value/item. Commonly, we say that an Observable emits an item, but we understand the same from an Observable sends a value as well.

By emit/send we mean that an Observable is calling the onNext method on an observer.

When talking about Observables, we use terms such as send error/complete notification/signal. We also often mention that an Observable completes, which means that an Observable has sent a complete notification.

By notification/signal we mean that an Observable is calling the onError or onComplete method on an observer.

In the preceding paragraph, we worked with a simple RxPHP demo that had one Observable, two operators and one observer.

This structure formed an operator/Observable chain. We'll understand the same thing from both of the terms operator chain and Observable chain (sometimes also referred to as a chain of Observable...

Components of RxPHP

Since this chapter is going to be mostly about Observables, observers and operators, we're going to start with them.

We've already seen a sneak peak in this chapter, and now we'll go into more detail.

Observables

Observables emit items. In other words, Observables are sources of values. Observers can subscribe to Observables in order to be notified when the next item is ready, all items have been emitted, or an error has occurred.

The main difference between an Observable (in the sense of reactive programming) and the observer pattern is that an Observable can tell you when all of the data has been emitted and when an error occurs. All three types of events are consumed by observers.

RxPHP comes with several basic types of Observables for general usage. Here are a few that are easy to use:

  • ArrayObservable: This creates an Observable from an array and emits all values right after the first observer subscribes.
  • RangeObservable: This generates a sequence of numbers...

Writing the DebugSubject class

One common use case for Subject class is proxying all values and notifications from its source Observable.

In one of the preceding paragraphs, we wrote the PrintObserver class, which prints all values it receives. However, a more common situation is where we want to output values from an Observable while being able to chain it with another operator or observer. The Subject class exactly fits this use case, so we'll rewrite the preceding PrintObserver class and inherit Subject instead of AbstractObserver:

class DebugSubject extends Rx\Subject\Subject { 
  public function __construct($identifier=null, $maxLen=64){ 
    $this->identifier = $identifier; 
    $this->maxLen = $maxLen; 
  } 
  public function onCompleted() { 
    printf("%s%s onCompleted\n", $this->getTime(), $this->id());
    parent::onCompleted(); 
  }  
  public function onNext($val) { 
    $type = is_object($val) ? get_class($val) : gettype($val); 
 
 ...

Basic principles of Reactive Extensions


Let's have a look at a very simple example of RxPHP, similar to what we did in the previous chapter, and use it to demonstrate some of the basic principles behind Reactive Extensions.

We won't bother with defining an observer right now and will focus only on Observables and operators:

// rxphp_basics_01.php 
use Rx\Observable; 
$fruits = ['apple', 'banana', 'orange', 'raspberry']; 
 
Observable::fromArray($fruits) // Observable 
    ->map(function($value) { // operator 
        return strlen($value); 
    }) 
    ->filter(function($len) { // operator 
        return $len > 5; 
    }) 
    ->subscribe($observer); // observer 

In this example, we have one Observable, two operators and one observer.

An Observable can be chained with operators. In this example, the operators are map() and filter().

Observables have the subscribe() method that is used by observers to start receiving values...

Naming conventions in Reactive Extensions


When talking about Observables, we use terms such as emit/send value/item. Commonly, we say that an Observable emits an item, but we understand the same from an Observable sends a value as well.

By emit/send we mean that an Observable is calling the onNext method on an observer.

When talking about Observables, we use terms such as send error/complete notification/signal. We also often mention that an Observable completes, which means that an Observable has sent a complete notification.

By notification/signal we mean that an Observable is calling the onError or onComplete method on an observer.

In the preceding paragraph, we worked with a simple RxPHP demo that had one Observable, two operators and one observer.

This structure formed an operator/Observable chain. We'll understand the same thing from both of the terms operator chain and Observable chain (sometimes also referred to as a chain of Observable operators). This is because, from our perspective...

Components of RxPHP


Since this chapter is going to be mostly about Observables, observers and operators, we're going to start with them.

We've already seen a sneak peak in this chapter, and now we'll go into more detail.

Observables

Observables emit items. In other words, Observables are sources of values. Observers can subscribe to Observables in order to be notified when the next item is ready, all items have been emitted, or an error has occurred.

The main difference between an Observable (in the sense of reactive programming) and the observer pattern is that an Observable can tell you when all of the data has been emitted and when an error occurs. All three types of events are consumed by observers.

RxPHP comes with several basic types of Observables for general usage. Here are a few that are easy to use:

  • ArrayObservable: This creates an Observable from an array and emits all values right after the first observer subscribes.

  • RangeObservable: This generates a sequence of numbers from a predefined...

Writing the DebugSubject class


One common use case for Subject class is proxying all values and notifications from its source Observable.

In one of the preceding paragraphs, we wrote the PrintObserver class, which prints all values it receives. However, a more common situation is where we want to output values from an Observable while being able to chain it with another operator or observer. The Subject class exactly fits this use case, so we'll rewrite the preceding PrintObserver class and inherit Subject instead of AbstractObserver:

class DebugSubject extends Rx\Subject\Subject { 
  public function __construct($identifier=null, $maxLen=64){ 
    $this->identifier = $identifier; 
    $this->maxLen = $maxLen; 
  } 
  public function onCompleted() { 
    printf("%s%s onCompleted\n", $this->getTime(), $this->id());
    parent::onCompleted(); 
  }  
  public function onNext($val) { 
    $type = is_object($val) ? get_class($val) : gettype...

Writing JSONDecodeOperator


We're going to work with calls to remote API's a few times throughout this book, so it would be very handy to have an operator that transforms JSON string responses into their PHP array representations.

This example looks like something that could be easily done with just the map() operator:

// rxphp_06.php  
Rx\Observable::just('{"value":42}') 
    ->map(function($value) { 
        return json_decode($value, true); 
    }) 
    ->subscribe(new DebugSubject()); 

This prints the correct result for sure, as we can see in the following output:

$ php rxphp_06.php
16:39:50 [] onNext: {"value": 42} (array)
16:39:50 [] onCompleted

Well, but what about malformed JSON strings? What happens if we try to decode the following:

Rx\Observable::just('NA') 
    ->map(function($value) { 
        return json_decode($value, true); 
    }) 
    ->subscribe(new DebugSubject()); 

The function json_decode() doesn't throw...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop an interesting multiplayer browser game written in RxJS and re-implement it using RxPHP
  • Enhance existing reactive applications by building a CLI tool combining Symfony Console
  • Implement Gearman and Rabbit MQ for asynchronous communication

Description

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.

Who is this book for?

This book is aimed at people with a solid knowledge of PHP and programming languages in general. We also assume they have at least a little experience with other technologies such as JavaScript, Node.js, and others.

What you will learn

  • How to work with the RxPHP library and see what it offers via many examples
  • Use the RxPHP library in combination with Symfony Console
  • The different approaches to using Symfony3 s Event Dispatcher component
  • Test your reactive PHP code using PHPUnit
  • Analyze PHP source code and apply a custom set of rules by building a CLI tool

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 24, 2017
Length: 364 pages
Edition : 1st
Language : English
ISBN-13 : 9781786461575
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Mar 24, 2017
Length: 364 pages
Edition : 1st
Language : English
ISBN-13 : 9781786461575
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 146.97
PHP 7 Data Structures and Algorithms
$48.99
PHP Microservices
$48.99
PHP Reactive Programming
$48.99
Total $ 146.97 Stars icon

Table of Contents

10 Chapters
1. Introduction to Reactive Programming Chevron down icon Chevron up icon
2. Reactive Programming with RxPHP Chevron down icon Chevron up icon
3. Writing a Reddit Reader with RxPHP Chevron down icon Chevron up icon
4. Reactive versus a Typical Event-Driven Approach Chevron down icon Chevron up icon
5. Testing RxPHP Code Chevron down icon Chevron up icon
6. PHP Streams API and Higher-Order Observables Chevron down icon Chevron up icon
7. Implementing Socket IPC and WebSocket Server/Client Chevron down icon Chevron up icon
8. Multicasting in RxPHP and PHP7 pthreads Extension Chevron down icon Chevron up icon
9. Multithreaded and Distributed Computing with pthreads and Gearman Chevron down icon Chevron up icon
10. Using Advanced Operators and Techniques in RxPHP Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 100%
1 star 0%
notgoingtoconsomeoneelse Jun 19, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Buyer Beware ! Published March 2017 - all examples are for RxPHP 1, when RxPHP 2 is now released ( June 2017) making most of the examples in this book redundant less than 3 months after publish date. Save your money and do not buy this book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.