Definition of PHP async
Async here stands for Asynchronous which means the process is not synchronous. Asynchronous allows the parallel execution of the code. That means we can run the piece of code separately and independent of each other this is called async process in general and this is the same in PHP also. We have the Async model in PHP which allows us to have multi task execution at the same time. It makes the execution of the code faster and increases the performance as well.
Syntax:
In PHP we can use the Spatie package to make use of the async feature. By this package, we can create a pool that will handle our async call and help us providing the parallel execution of the program. For better understating we can have look at the syntax see below;
//package to be used
use Spatie\Async\Pool;
$mypool = Pool::create();
$mypool[] = async() {
//your logic goes here
})->then() {
// your logic
});
First, we need to import the package which is ‘Spatie\Async\Pool’ here. After that, we are creating a pool that will handle the async operations for us. Followed by ‘async’ keyword inside this we will write our whole logic and piece of code that we want to run in parallel. Here we have a ‘then’ method which is a callback method inside this we can also write our own logic. After all the operation we can write some more operations on the given output in ‘then’ block.
How async Function Works in PHP?
As now we know that the async function allows us the execution of multiple tasks. If we talk about the Synchronous programming in PHP, so we will always have output in the same order. suppose we want to print the number from 1 to 10. So if I write this logic using the Synchronous code I will always get in ascending order. But if we try to use the async code here for the same logic then we are not sure about the order of number. We will discuss this in more detail with some examples below. To write the async code in PHP we have used one package called ‘spatie’. This also provides us better handling of error and exceptions in async code. First, we will see how we can write a simple logic using this package. Then we will discuss the more methods that can be used with async code in detail later on.
- In order to create the async block, we first need to import or use the package ‘spatie’. We can import this in our code like below; We will install this package by using the composer. You can find the composer command as well below the syntax.
Example:
use Spatie\Async
cmd:
composer require spatie
- The second step is that we will create a pool object. By using this object we can write the async function. See syntax below for better understanding;
Example:
$mypool = Pool::create();
We can give any name to the pool object also do not forget to import the Pool class present inside ‘Async’. See below;
Example:
use Spatie\Async\Pool;
- In this step, we can now create our async function using the pool object. We can give any name to the function and write our logic. For better understating see below the syntax;
Example:
demoAsync(function () {
// //
})
->then(function ($output) {
// //
})
In the above piece of code, we are creating an async function and using its callback method ‘then’. This ‘then’ function is responsible to operate when the above block of code executed successfully. If not, then we need to handle that case by using other methods of Async.
Now we will see some methods which can handle the error, exception, and timeouts which can occur while execution of the code. This package provides us various methods to handle this inside the async block of the code. Let’s discuss each of them in detail see below;
1. timeout
This method will be executed when the block of code does not perform its operations and taking more time than usual. So this method will be executed. Syntax to write this method is shown below;
Example:
timeout(function () {
// when timeout reached.
})
2. then
This method will be executed if the block of code gets executed successfully and we are ready to perform more operations on the result. Syntax to write this method is shown below;
Example:
then(function ($result) {
// operation after result
})
3. catch
This method will be executed if the block of code throws an exception. Inside this method, we can handle them and perform our logic. Syntax to write this method is shown below;
Example:
catch(function ($exp) {
// exception can be handle here.
})
Examples of PHP async
Following are the examples as given below:
Example #1
In this example, we are implementing async with then method and just printing two messages to keep it simple for beginners.
Code:
use Spatie\Async\Pool;
$mypool = Pool::create();
$mypool
->asyncDemo(function () {
print("async called here !!")
})
->then(function () {
print("then called after result !!")
} ;
Output:
Example #2
In this example, we are using all the methods of async from the Spatie\Async\ package. Those are catch, then and timeout. We keep it simple for now without too much logic.
Code:
use Spatie\Async\Pool;
$mypool = Pool::create();
$mypool
->asyncDemo(function () {
print("async called here !!")
print("async called here !!")
})
->then(function ($output) {
print("print called here !!")
})
->catch(function ($exception) {
print("catch called here !!")
})
->timeout(function () {
print("timeout called here !!")
})
;
Output:
Conclusion
By using async in our code we can enable parallel execution of tasks in our program. Also, they increase the performance of the code because the piece of code is independent of each other. But we cannot use this where data from the previous block of code is dependent on the current otherwise there will be a loss of data occurred and it will not be consistent.
Recommended Articles
This is a guide to PHP async. Here we also discuss the definition and how async function works in php? along with different examples and its code implementation. You may also have a look at the following articles to learn more –
5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses