Home  >  Article  >  Backend Development  >  PHP async

PHP async

WBOY
WBOYOriginal
2024-08-29 12:51:451116browse

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 independently of each other. This is generally called the async process, and this is the same in PHP. We have the Async model in PHP, which allows us to have multi-task execution simultaneously. It makes the execution of the code faster and increases the performance as well.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

In PHP, we can use the Spatie package to use the async feature. With this package, we can create a pool that will handle our async call and help us provide the parallel execution of the program. For better understating, we can have a 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 ‘SpatieAsyncPool’ 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 operations, we can write more operations on the given output in the ‘then’ block.

How async Function Works in PHP?

Now we know that the async function allows us the execution of multiple tasks. If we talk about 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 it 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 with better handling of errors and exceptions in async code. First, we will see how to 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 the syntax below for a 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 for operating when the above code block is executed successfully. If not, then we need to handle that case by using other methods of Async.

Now we will see some methods to handle the error, exceptions, and timeouts that can occur while executing the code. This package provides us with various methods to handle this inside the async block of the code. Let’s discuss each of them in detail. See below;

1. timeout

The method will be executed when the block of code fails to perform its operations within the expected timeframe or encounters an error. The following is the syntax to write this method:

Example:

timeout(function () {
// when timeout reached.
})

2. then

The method will be executed if the block of code is executed successfully and there is a need to perform additional operations on the result. The following is the syntax to write this method:

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. The 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 given below:

Example #1

In this example, we are implementing async with the method and 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:

PHP async

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:

PHP async

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 using StopIteration in situations where the data from the previous block of code is dependent on the current can lead to data loss and inconsistency.

The above is the detailed content of PHP async. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP strlen()Next article:PHP strlen()