
www.phparch.com October 2020 Volume 19 - Issue 10 Parallel Running Build An All-In-One Application Server Using Swoole More Than Asynchronous I/O, Introduction To Swoole PHP Serverless File Uploading Education Station: The Workshop: Security Corner: Race Conditions and PHP Development with Observable Security Dead Locks Homestead in WSL PHP Puzzles: Community Corner: Sustainable PHP: Improved Directions ALSO INSIDE Larabelles Refactor to Competitive finally{}: Advantage Async Life a php[architect] anthology Learn how a Grumpy Programmer approaches testing PHP applications, covering both the technical and core skills you need to learn in order to make testing just a thing you do instead of a thing you struggle with. The Grumpy Programmer’s Guide To Testing PHP Applications by Chris Hartjes (@grmpyprogrammer) provides help for developers who are looking to become more test-centric and reap the benefits of automated testing and related tooling like static analysis and automation. Available in Print+Digital and Digital Editions. Order Your Copy phpa.me/grumpy-testing-book Build a custom, secure, multilingual website with WordPress WordPress is more than a blogging platform—it powers one-fifth of all sites. Since its release, enthusiastic contributors have pushed the en- velope to use it as a platform for building specialized social networks, e-commerce storefronts, business sites, and more. This guide helps you sort through the vast number of plugins available to find the ones that work for you. You’ll also learn how to use CSS and PHP code to tailor WordPress to your needs further. Written by PHP professionals Peter MacIntyre and Sávio Resende, this book distills their experience building online solutions for other Word- Press site builders, developers, and designers to leverage and get up to speed quickly. Read a sample and purchase your copy at the link below. Order Your Copy http://phpa.me/wpdevdepth-book FEATURE More Than Asynchronous I/O, Introduction To Swoole PHP Bruce Dou Swoole PHP is a coroutine based asynchronous network application framework. It is a PHP extension that extends PHP core and utilizes more power provided by Linux OS. Unlike the callback style single thread asynchronous I/O provided by the other networking libraries like Node.js, Swoole PHP has multiple asynchronous I/O threads and native coroutines to manage the execution of concurrent tasks. Other than asynchronous I/O and coroutine, we can also use the Linux system API and interface exposed by Swoole PHP, such as process management, system signals handling, timer and scheduler, poll and epoll I/O, memory management, etc. What Problem Does Swoole PHP Solve? The First Glance: HTTP Echo Server Swoole PHP1 is designed for building large scale concur- Let’s start with an echo server with HTTP protocol shown rent systems. The system needs to manage more than 10K in Listing 1, which processes an HTTP request and sends concurrent connections. It is a solution to the famous C10K back a hello world HTTP response to a browser or HTTP problem with PHP and a stateful architecture. client. It is executed as a PHP CLI application. Use a port We cannot use PHP-FPM’s stateless nature to build a number more than 1024 if you like to run the application as system with modern web protocols like WebSockets, which a non-root user. require establishing persistent connections with every user Compared with PHP-FPM applications we are familiar and sending, receiving data in real-time. with, there is a bit more boilerplate code. We have to define With Swoole PHP, building a real-time service is as simple a server with an IP address, port to bind on first, and then as building PHP-FPM applications we are familiar with. You define how we process the HTTP request. It gives us more can define how to respond to requests in the predefined call- flexibility since we can choose the IP address, port, protocol back functions to build a WebSocket server or TCP/UDP at the PHP application layer. Traditional PHP applications server with only several lines of code. that sit behind a web server couldn’t change those values. Compared with the other single thread callback style When the server starts, it initializes several reactor threads asynchronous I/O frameworks built with PHP or JavaScript, implemented with epoll in Linux or kqueue in OSX to Swoole is released as a PHP extension, including high-per- perform non-blocking I/O operations. Event loops manage formance protocol parsers written with C/C++, multiple the status of file descriptors in these reactor threads. Swoole asynchronous I/O handling threads, native lightweight thread coroutine, and multiple processes architecture. Listing 1. Swoole PHP also exposes the under layer Linux API to 1. <?php the PHP layer. With it, we can use PHP to build system-level 2. declare(strict_types=1); software. 3. It is not designed to replace the stateless PHP-FPM but as 4. use Swoole\HTTP\Server; a different and additional stateful programming model for 5. use Swoole\Http\Request; 6. use Swoole\Http\Response; PHP developers and system architects. Unlike PHP-FPM, 7. a Swoole application is started as a Linux process you can 8. $server = new Server("0.0.0.0", 9900); define with PHP code. If you are not deploying it with Docker, 9. you can use a Linux process manager such as supervisord or 10. $server->on("request", systemd to manage the Swoole application. 11. function (Request $request, Response $response) { 12. $response->header("Content-Type", "text/plain"); Swoole PHP provides coroutine and asynchronous I/O for 13. $response->end("Hello World\n"); concurrent programming, which we can use to manage thou- 14. } sands of persistent concurrentSample connections either as a server 15. ); or as a client with only one process. 16. 17. $server->start(); 1 Swoole PHP: https://www.swoole.co.uk 8 \ October 2020 \ www.phparch.com More Than Asynchronous I/O, Introduction To Swoole PHP doesn’t support Windows OS unless you run it inside a Linux Listing 2. environment with Docker. To better utilize the power of the multiple CPU cores, we 1. <?php create numerous worker processes to serve the requests 2. declare(strict_types=1); sent to the server. The data received by reactor threads are 3. 4. use Swoole\Server; dispatched to the callback functions in the worker processes 5. registered on the server. 6. $server = new Server("0.0.0.0", 9900); We can also write similar code to create a Server speaking 7. with other protocols such as TCP, UDP, WebSocket, MQTT, 8. $server->on("receive", etc. The code in Listing 2 is a similar server with TCP protocol. 9. function (Server $server, int $fd, 10. int $reactor_id, string $data) { If we build a similar TCP server with socket API provided 11. $server->send($fd, "Hello: {$data}"); by PHP, there will be much more boilerplate code, and 12. $server->close($fd); you have to understand how Linux sockets work. You can 13. } compare the above code with the PHP sockets example2. 14. ); 15. You can send a TCP package hey to the server with Netcat nc 16. $server->start(); and receive the response generated by the server: Hello: hey. (echo 'hey'; sleep 1) | nc 127.0.0.1 9900 Listing 3. You can define a custom protocol using the TCP protocol specifically fitting for your application to reduce HTTP overhead. 1. <?php 2. declare(strict_types=1); Event Emitter And Timer 3. 4. use Swoole\HTTP\Server; When thinking about web applications, the execution 5. use Swoole\Http\Request; can be triggered by an HTTP request or triggered by some 6. use Swoole\Http\Response; predefined events or rules. 7. For example, many PHP applications perform house- 8. $server = new Server("0.0.0.0", 9900); 9. keeping jobs with fixed intervals like sending the daily email, 10. $server->on("workerStart", sending a queued email, refreshing caches, recalculating a 11. function (Server $server, int $worker_id) { billboard, or pushing fresh data to the user’s browser. 12. if ($worker_id === 0) { We can do this with Linux CRON jobs to simulate user 13. $server->tick(1000, function () { requests by sending an HTTP request to the HTTP applica- 14. echo time() . "\n"; tion, or run a PHP CLI script to avoid the HTTP server-side 15. }); timeout limitation. But this approach relies on an external 16. } 17. } system CRON with a minimum minute interval scheduler. To 18. ); CRON sleep schedule second interval tasks with , is required, 19. which is more complex and inconvenient. 20. $server->on("request", In Swoole PHP, we can define a ticker executed every 21. function (Request $request, Response $response) { second or even every millisecond within Server and start the 22. $response->header("Content-Type", "text/plain"); ticker with the Server, see Listing 3. 23. $response->end("Hello World\n"); 24. } worker Notice the ticker only executes in one , which is the 25. ); one with worker_id of 0 (zero). As mentioned before, the 26. server creates multiple worker processes, and we only want 27. $server->start(); the events to be triggered once per second. Otherwise, all the worker threads would fire every second. PHP-FPM helps us to manage multiple PHP processes With the ability to trigger an event every second or every serving the HTTP requests. So, we don’t have to think about millisecond, we can build near-real-time applications. Process Management when writing PHP applications. The downside is that we cannot define or customize how PHP Compare With PHP-FPM processes are launched or managed with PHP. PHP-FPM is a stateless design; the whole context is created Swoole PHP runs as a PHP CLI application.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages10 Page
-
File Size-