Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Sergey Zhuk:
Sending Email Asynchronously With ReactPHP Child Processes
May 04, 2018 @ 14:42:27

Sergey Zhuk has a new tutorial posted on his site showing you how to use child processes in ReactPHP to send emails asynchronously using Swiftmailer.

In PHP the most of libraries and native functions are blocking and thus they block an event-loop. For example, each time we make a database query with PDO, or check a file with file_exists() our asynchronous application is being blocked and waits. Things often become challenging when we want to integrate some synchronous code in an asynchronous application. This problem can be solved in two ways: rewrite a blocking code using a new non-blocking one or fork this blocking code and let it execute in a child process, while the main program continues running asynchronously.

This first approach is not always available, asynchronous PHP ecosystem is still small and not all use-cases have asynchronous implementations. So, in this article, we will cover the second approach.

He starts by creating the main HTTP server handler running locally on port 8080. He adds in an exception handler to catch potential issues and provides example code of an exception being thrown. With that structure in place he starts on the Swiftmailer integration, adding it to the exception handler and pushing the details of the exception into the message body. This is then modified to use the react/child-process package to wrap a new PHP file inside of a child process loop. The tutorial ends with an example of how to pass data between the parent and child process. In this case it's the message from the exception.

tagged: send email child process reactphp tutorial exception asynchronous

Link: http://sergeyzhuk.me/2018/05/04/reactphp-child-processes/


Trending Topics: