Chapter 9.  Reactive Extensions in PHP

In this chapter, we'll talk about Reactive extensions in PHP, a PHP library that allows PHP programmers to work with PHP in a reactive manner, and how to use in event, also known as publish-subscribe programming. We'll also discuss the idea of functional programming in PHP and how to program in a more succinct way. We will also discuss the following topics:

  • Map
  • Reduce
  • Defer
  • Reactive extensions in the following use cases:
    • Data analysis of logs (parsing Apache logs)
    • Queueing systems (asynchronously working through a queue of tasks)
    • Events

Reactive extensions are a way to code in a functional way using PHP. They are a set of libraries (available on GitHub at https://github.com/ReactiveX/RxPHP) that can help you compose event-based programs by using observable collections and LINQ-style query operators in PHP.

An introduction to observables

In short, you will be doing event-driven programming, where you will work with what's called as the event loop, and attaching (hooking up) events to do your bidding.

Installation is a simple composer that is required is all.

How does Reactive PHP work? In PHP, there is no such way to create a server except when running the code php -S localhost:8000. PHP will treat the current directory as the basis of the public directory (in Apache, usually this is /var/www or C:/xampp/htdocs when using  XAMPP). This, by the way, has been available since PHP 5.4.0 only and also works with PHP 7.x.

There is no programmable way to control how that PHP command-line interface's server actually works.

Every time you send a request to that server, PHP server will be in charge of handling whether it's a valid request, and handle the event by itself. In short, every request is a new request-there's no streaming or events that get involved.

RxPHP works by creating an event loop by creating a PHP stream under the hood, which has added functions that help make Reactive Programming possible. The stream basically has a recursive function (a function that keeps calling itself and creates a loop of commands, in essence). An event loop is basically a programming construct that runs an infinite loop, which simply waits for events and be able to react (in other words, run some function) to each of those events.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.200.220