Table of Contents
Remote calling principle
Benefits of remote calling
What is the difference between RPC and Socket?
What is the difference between RPC and REST?
What are the popular RPC frameworks in php
phprpc
Installation
Start using
yar
Download and install
Home Backend Development PHP Tutorial Detailed explanation of popular rpc framework in php

Detailed explanation of popular rpc framework in php

Mar 19, 2018 pm 02:31 PM
php frame Detailed explanation

What is the RPC framework? If RPC can be summarized in one sentence: Remote Procedure Call, then what is remote call? Usually we call a method in PHP, such as this function method: localAdd(10, 20). The specific implementation of the localAdd method is either defined by the user or comes with the PHP library function, that is, in the localAdd method The code is implemented locally, it is a local call! Remote calling means: the specific implementation of the called method is not where the program is running, but in some other remote place.

Remote calling principle

For example, A (client) calls the remoteAdd method provided by B (server):

  1. First, establish a connection between A and B TCP connection;

  2. Then A serializes the method name that needs to be called (remoteAdd here) and method parameters (10, 20) into a byte stream and sends it out;

  3. B accepts the byte stream sent by A, then deserializes it to obtain the target method name and method parameters, then executes the corresponding method call (possibly localAdd) and returns the result 30;

  4. A accepts the remote call result and outputs 30.

The RPC framework encapsulates the details I just mentioned and exposes users to simple and friendly API usage.

Benefits of remote calling

Decoupling: When the server needs to modify the method, the client is completely unaware and does not need to make any changes; this method is suitable for cross-department and cross-company cooperation. It is often used, and the provider of the method is usually called: service exposure.

What is the difference between RPC and Socket?

Through the above simple explanation, it seems that RPC and Socket are similar. They all call remote methods and are all in client/server mode. I also wrote an article before: Talking about sockets in detail. So what are the differences between them?

RPC (remote procedure call) uses client/server Mode enables two processes to communicate with each other. Socket is one of the communication methods often used by RPC. RPC is implemented on the basis of Socket. It requires more network and system resources than Socket. In addition to Socket, RPC also has other communication methods, such as http, the operating system's own pipeline and other technologies to implement calls to remote programs. In Microsoft's Windows system, RPC uses named pipes for communication.

What is the difference between RPC and REST?

After understanding RPC, we know that RPC is in client/server mode and calls remote methods. REST is also a set of API calling protocol methods that we are familiar with. It is also based on client/server mode and calls remote methods. method, so what’s the difference between them?

REST API and RPC both encapsulate functions into interfaces on the Server side and expose them for calls by the Client. However, the REST API is based on the HTTP protocol, and REST is committed to passing the POST/ GET/PUT/DELETE and other methods and a human-readable URL to provide an http request. RPC does not need to be based on the HTTP protocol
Therefore, if the two back-end languages ​​call each other, using RPC can achieve better performance (eliminating a series of things such as HTTP headers), and it should be easier to configure. If the front end calls the back end through AJAX, it is better to use the REST API (because you cannot avoid the HTTP hurdle anyway).

Since php is the best language in the world, what are the popular RPC frameworks in php?

Let’s list them first: phprpc, yar, thrift, gRPC, swoole, hprose

Because time and energy are limited, it is impossible to learn and use them one by one. I will choose a few that are commonly used in the world. Let’s use the ones with the most. Because the principle of RPC is the same, both are Client/Server mode, but the usage of each framework is different.

Mainly explain phprpc and yar, which I have heard about and come into contact with the most so far.

phprpc

First download the latest stable version of phprpc from the official website: download link and unzip.

Installation

We will find that there are many files and folders inside, with the following structure:

  • dhparams/

  • pecl/

  • bigint.php

  • compat.php

  • phprpc_date.php

  • xxtea.php

  • ##dhparams.php

  • phprpc_server.php

  • phprpc_client.php

Among them, dhparams and pecl are folders, and pecl is the xxtea extension of php, as described on the official website , you can install it or not, and it can run without installing phprpc. But if you need faster encryption processing capabilities, you can install it.

I’d better install it. After all, the encryption capability is faster, which is a good thing:

The installation steps are as follows, first copy the xxtea folder under pecl to the etx directory of the php source code: /lamp/php-5.4.11/ext. Then use phpize to recompile with extensions.

[root@localhost /]# cd /lamp/php-5.4.11/ext/xxtea
[root@localhost xxtea]# /usr/local/php/bin/phpize
[root@localhost xxtea]# ./configure --enable-xxtea=shared --with-php-config=/usr/local/php/bin/php-config
make && make install
Copy after login

OK, the compilation is completed, prompting us that xxtea.so is already in /usr/local/php/lib/php/extensions/no-debug-zts-20100525/xxtea.so.

Next, we need to add this xxtea.so at the end of php.ini:

[root@localhost /]# vi /usr/local/php/etc/php.ini 
[xxtea]
extension=xxtea.so
Copy after login

Okay. After adding it, we need to restart apache or php-fpm

重启apache
[root@localhost /]# /usr/local/apache/bin/apachectl restart
平滑重启php-fpm
kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
Copy after login
Copy after login

After the restart, open the phpinfo() page, search, and you should be able to see xxtea.

Start using

Let’s take a simple example first. phprpc is also divided into server and client. So the corresponding files in the folder are phprpc_server.php and phprpc_client.php

Let’s refer to several examples on the official website and practice:

server.php Server side: Writing this way will complete a final Simple helloword interface.

<?php
include ("phprpc/phprpc_server.php");
function HelloWorld() {
   return &#39;Hello World!&#39;;
}
$server = new PHPRPC_Server();
$server->add(&#39;HelloWorld&#39;);
$server->start();
Copy after login

Run server.php, I wiped it, and an error was reported! ! !

PHP Strict Standards:  Non-static method PHPRPC_Server::initSession()....
Cannot redeclare gzdecode().....
Copy after login

Googled it, and it said that they first changed the initSession() in line 413 of phprpc_server.php to a static function

 static function initSession() {
    ****
 }
Copy after login

PS. I was surprised, such a big mistake, phprpc is How to publish it! ! !

In the gzdecode() function on line 71 of compat.php, php5.4 has already implemented this function. In this way, the function is rewritten and an error is reported, so add a judgment:

if (!function_exists(&#39;gzdecode&#39;)) {
    //将gzdecode函数包括进来
}
Copy after login

Okay. After making changes, save. Run server.php again. OK. No more errors. Output:

phprpc_functions="YToxOntpOjA7czo5OiJoZWxsb3dvcmQiO30=";
Copy after login

Let’s write the client client.php next. Let’s see how it is written?

<?php
include ("phprpc/phprpc_client.php");
$client = new PHPRPC_Client(&#39;http://127.0.0.1/server.php&#39;);
echo $client->HelloWorld();
?>
Copy after login

We are executing the following client.php, and the output is as expected:

Hello Word!
Copy after login

Such a simple Server/Clent delivery is completed. Although there were some mistakes in the middle, it is generally quite simple and easy to understand!

For other more advanced usage, please refer to the official website.

yar

yar is the masterpiece of Hui Xinchen, the famous PHP master in China, and has been used in Weibo products. It is also an rpc framework. Because it uses an extension for PHP written in pure C, the efficiency should be quite high, and it supports asynchronous parallelism, which is quite good.

Download and install

Official website download: http://pecl.php.net/package/yar The latest version yar-1.2.4.tgz

Then unzip and copy to The etx directory of the php source code: /lamp/php-5.4.11/ext. Then use phpize to recompile with extensions.

[root@localhost yar-1.2.4]# /usr/local/php/bin/phpize
[root@localhost yar-1.2.4]# ./configure --with-php-config=/usr/local/php/bin/php-config
Copy after login

But there is a problem: prompt, there is a problem with curl:

configure: error: Please reinstall the libcurl distribution - easy.h should be in <curl-dir>/include/curl/
Copy after login

It is estimated that there is a problem with my local curl, then use yum to install it:

yum -y install curl-devel
Copy after login

Installation After completing curl, continue compiling and installing, and there will be no problem:

[root@localhost yar-1.2.4]# /usr/local/php/bin/phpize
[root@localhost yar-1.2.4]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@localhost yar-1.2.4]# make && make install
Copy after login

After success, we will be prompted that the yar.so extension is already in /usr/local/php/lib/php/extensions/no-debug-zts -20100525/ is down.

We vi edit php.ini, add the yar.so extension at the end, and then restart apache or php-pfm.

[root@localhost /]# vi /usr/local/php/etc/php.ini 
[yar]
extension=yar.so
Copy after login

Okay. After adding it, we need to restart apache or php-fpm

重启apache
[root@localhost /]# /usr/local/apache/bin/apachectl restart
平滑重启php-fpm
kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
Copy after login
Copy after login

After the restart, open the phpinfo() page, search, and you should be able to see yar.

Start using

Like other rpc frameworks, yar is also in server/client mode, so we will do the same and start writing a simple example to show how to call it.

yar_server.php represents the server side

<?php
class API {
   public function api($parameter, $option = "foo") {
       return $parameter;
   }
   protected function client_can_not_see() {
   }
}
$service = new Yar_Server(new API());
$service->handle();
Copy after login

Okay, let’s run it in the browser, and the output as shown below will appear. Very high-end! ! ! Brother Niao said that the purpose of this is to know at a glance how many interfaces my rpc provides, and the api documentation can be omitted.

Detailed explanation of popular rpc framework in php

Okay, let’s start writing yar_client.php. This is the client:

$client = new Yar_Client("http://127.0.0.1/yar_server.php");
echo $client->api(&#39;helo word&#39;);
Copy after login

Okay, like other swoole, hprose, etc., this principle is basically the same. It just depends on which one has more functions and is easier to use.

Related recommendations:

The RPC framework in PHP implements a flow control system based on Redis

Detailed examples of RPC framework

Detailed code explanation of PHP remote calling and RPC framework (picture)

The above is the detailed content of Detailed explanation of popular rpc framework in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles