EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP async

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP async

PHP async

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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;

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,077 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

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:

PHP async-1.1

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-1.2

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 –

  1. PHP array_pop()
  2. PHP implode
  3. PHP Split String
  4. PHP URL

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP list
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP strpos
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • PHP Object Injection
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Builder
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • Sort string PHP
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • PHP Open File
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More