O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHP Reactive Programming

Book Description

Leverage the power of Reactive Programming in PHP

About This Book

  • 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

Who This Book Is 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

In Detail

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.

Style and approach

This book will teach readers how to build reactive applications in a step-by-step manner. It will also present several examples of reactive applications implemented with different frameworks.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

Table of Contents

  1. PHP Reactive Programming
    1. PHP Reactive Programming
    2. Credits
    3. About the Author
    4. About the Reviewer
    5. www.PacktPub.com
      1. Why subscribe?
    6. Customer Feedback
    7. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    8. 1. Introduction to Reactive Programming
      1. Imperative programming
      2. Declarative programming
      3. Sequential and parallel programming
      4. Asynchronous programming
        1. Asynchronous versus parallel programming
      5. Functional programming
        1. Functional programming in PHP
          1. Eliminating side effects
          2. Avoiding mutable data
          3. First-class citizens and higher-order functions
          4. Anonymous functions in PHP
          5. PHP magic methods
      6. Reactive programming
        1. jQuery Promises
        2. Gulp streaming build system
        3. EventDispatcher component in PHP
      7. Reactive Extensions
        1. Autocomplete with RxJS
        2. Mouse position on drag and drop
      8. Introducing RxPHP
        1. RxPHP 1.x and RxPHP 2
      9. Summary
    9. 2. Reactive Programming with RxPHP
      1. Basic principles of Reactive Extensions
      2. Naming conventions in Reactive Extensions
      3. Components of RxPHP
        1. Observables
        2. Observers
        3. Singles
        4. Subject
        5. Disposable
        6. Scheduler
        7. Operators
          1. Understanding the operator diagrams
            1. The filter() operator
            2. The debounceTime() operator
            3. The concat operator
          2. Other common operators
      4. Writing the DebugSubject class
      5. Writing JSONDecodeOperator
        1. Simplifying propagation of notifications
        2. Using custom operators in RxPHP 2
      6. Writing CURLObservable
        1. Imperative approach and cURL
        2. Implementing cURL into a custom Observable
          1. Running multiple requests asynchronously
      7. The proc_open() and non-blocking fread()
      8. Event loop and RxPHP
      9. Summary
    10. 3. Writing a Reddit Reader with RxPHP
      1. Examining RxPHP's internals
        1. A closer look at subscribing to Observables
          1. Emitting multiple values with Schedulers
        2. A closer look at operator chains
          1. Subscribing to ConnectableObservable
          2. Using Subject instead of ConnectableObservable
      2. Observable::create() and Observable::defer()
        1. Creating Observables with Observable::create()
        2. Creating Observables with Observable::defer()
      3. Writing a Reddit reader using RxPHP
        1. Using the Symfony Console component
        2. Non-blocking user input and an event loop
        3. Subscribing to user inputs
      4. Non-blocking CURLObservable
        1. Using Symfony Process component
          1. The takeWhile() operator
        2. Implementing subprocesses into the Reddit reader app
      5. Types of disposable classes
      6. Summary
    11. 4. Reactive versus a Typical Event-Driven Approach
      1. Handling error states in operator chains
        1. The retry() operator
          1. CURLObservable and the retry() operator
        2. The retryWhen() operator
          1. CURLObservable and the retryWhen() operator
          2. CURLObservable and controlled number of retries
        3. The catchError() operator
      2. The concat() and merge() operators
        1. The merge() operator
        2. The concat() operator
        3. The concatMap() and flatMap() operators
      3. Writing a reactive event dispatcher
        1. A quick introduction to EventDispatcher
          1. Working with event listeners
          2. Working with event subscribers
        2. Writing ReactiveEventDispatcher with RxPHP
          1. Internal representation of event listeners as observers
        3. Writing a ReactiveEventDispatcher class
        4. Adding event listeners
        5. Adding Observables
        6. Adding event subscribers
        7. Creating the Observable chain for an event
          1. Comparing filter() to takeWhile()
        8. Dispatching events
        9. Practical example of ReactiveEventDispatcher
          1. Working with event listeners
          2. Working with event subscribers
      4. Summary
    12. 5. Testing RxPHP Code
      1. The doOn*() operators
      2. Installing the PHPUnit package
      3. Basics of writing tests using PHPUnit
        1. Testing asynchronous code
      4. Testing RxPHP code
        1. Introducing VirtualTimeScheduler
        2. HotObservable and ColdObservable
        3. MockObserver
        4. TestScheduler
      5. Testing SumOperator
      6. Testing ForkJoinObservable
      7. Summary
    13. 6. PHP Streams API and Higher-Order Observables
      1. Using Promises in PHP
        1. Using the then() and done() methods
        2. Using the otherwise() and always() methods
      2. PHP Streams API
        1. Using the stream_select() function
        2. StreamSelectLoop and stream_select() function
        3. Scheduling events with StreamSelectLoop
          1. Minimalistic HTTP Server with StreamSelectLoop
        4. A note on nonblocking event loops
        5. Using multiple StreamSelectLoop instances
          1. Event loop interoperability in PHP
          2. Event loops and future versions of RxPHP
      3. Higher-order Observables
        1. The concatAll() and mergeAll() operators
        2. The switchLatest Operator
        3. The combineLatest() operator
      4. Summary
    14. 7. Implementing Socket IPC and WebSocket Server/Client
      1. Backpressure in Reactive Extensions
        1. Lossy backpressure
          1. Implementing throttleTime() with the filter() operator
        2. Loss-less backpressure
      2. Implementing ProcessObservable
      3. Server Manager application
        1. Creating new subprocesses with ProcessObservable
        2. Game Server application
      4. Server Manager and the Unix socket server
        1. Implementing the GameServerStreamEndpoint class
        2. Displaying real-time statuses from subprocesses
          1. Combining the switchLatest() and combineLatest() operators
      5. Implementing a WebSocket server
      6. Implementing a WebSocket client
      7. Summary
    15. 8. Multicasting in RxPHP and PHP7 pthreads Extension
      1. Subjects
        1. BehaviorSubject
        2. ReplaySubject
        3. AsyncSubject
      2. Multicasting in RxPHP
        1. The multicast() operator and ConnectableObservable
        2. MulticastObservable
          1. Subjects and their internal state
        3. The multicast() operator and MulticastObservable
          1. Comparing ConnectableObservable and MulticastObservable
        4. The multicastWithSelector() operator
        5. The publish*() and share*() operator groups
          1. The refCount() operator
        6. The publish() and share() operators
        7. The publishValue() and shareValue() operators
        8. The replay(), shareReplay(), and publishLast() operators
      3. PHP pthreads extension
        1. Prerequisites
        2. Introduction to multithreading with pthreads in PHP7
        3. Getting/setting data from/to threads
        4. Using Thread, Worker, and Pool classes
          1. Retrieving results from thread pools
      4. RxPHP and pthreads
      5. Summary
    16. 9. Multithreaded and Distributed Computing with pthreads and Gearman
      1. Introduction to the PHP Parser library
        1. Using the PHP Parser library
        2. Implementing PHPParserOperator
          1. Writing AssignmentInConditionNodeVisitor
          2. Writing PHPParserOperator
      2. Implementing ThreadPoolOperator
        1. Implementing PHPParserThread
        2. Implementing PHPParserWorker
        3. Running PHP Parser in a multithreaded application
      3. Introduction to Gearman
        1. String strlen client and worker
        2. Running PHP Parser as a Gearman worker
        3. Comparing pthreads and Gearman
      4. Summary
    17. 10. Using Advanced Operators and Techniques in RxPHP
      1. The zip() operator
      2. The window() operator
      3. The materialize() and dematerialize() operators
        1. Customizing error bubbling with dematerialize()
      4. Error handling in RxPHP operator chains
        1. The default error handler
        2. Catching exceptions inside operators
      5. The Observable::create() method versus the Subject class
        1. Hot/cold Observables and Observable::create()
      6. Call stack length and EventLoopScheduler
      7. Unsubscribing versus completing an Observable
      8. Anonymous operators
      9. Writing a custom DirectoryIteratorObservable
        1. DirectoryIteratorSharedObservable
      10. FTP client with RxPHP
      11. Summary
    18. Appendix. Reusing RxPHP Techniques in RxJS
      1. What is RxJS?
        1. JavaScript module systems
        2. The deployment process of RxJS 5
      2. A quick introduction to RxJS 5 in Node.js
        1. Asynchronous calls in RxJS
        2. Node.js and asynchronous events
        3. Lossy backpressure with the debounceTime() operator
      3. Higher-order Observables in RxJS 5 and RxPHP
      4. Operators specific for RxJS 5
        1. The expand() operator
        2. The finally() operator
        3. The withLatestFrom() operator
        4. Caching HTTP requests with publishReplay() and take()
      5. Summary