Download the PHP package sebk/small-swoole-patterns without Composer
On this page you can find all versions of the php package sebk/small-swoole-patterns. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package small-swoole-patterns
small-swoole-patterns
This project provides implementations of async design patterns to open swoole projects.
Migrated
This lib has been migrated to framagit project.
A new composer package is available at https://packagist.org/packages/small/swoole-patterns
Future commits will be done on framagit.
This repository will be removed in few month.
Install
Install openswoole :
Require the package with composer:
Patterns
Array
Map
This is an evolution of swoole function \Coroutine\map
It is a class to map array on a callback. More verbose than \Coroutine\map but allow you waiting later in code.
Observable
This is an implementation of observable pattern on a callback.
In this example, we print homepage of google, yahoo and qwant on async calls.
Pool
This is an implementation of pool pattern.
Pools are useful to manage async processes in order to manage connections to server resources.
Create the Pool
Here we have created
- A PRedis client pool (first parameter)
- With a maximum of 10 clients at the same time (second parameter).
- If no more clients available, the pool try to lock a new client every 100µs (third parameter)
Using client process
To get a client, use get method :
You have now locked the client and can use it :
Now we have finished the use, we must release the client :
Putting together in async process will be :
In this use case, the number of concurrent connections can't be more than 10 connections at the same time even the process is async.
Using one client destroy the async advantages while using client will wait for previous end.
Using a new client at each time can overload your memory and server.
Rate control
You can control the server limitations using rate control.
Activating rate control
In this code, the pool is waiting you are getting clients no more than 100µs. If less, it will wait 10µs before retry.
Using rate control for server limitation
For this example, we will consider that you want to connect to a provider http api. You have a limitation of 3000 requests by minutes.
You can activate a unit control to observe the provider limitations even your code is faster :
Resource
You can manage resource access with resource pattern :
In async processes you can wait the others processes to unlock resource :
Or manage yourself the waiting process :