PHP实现协程
在服务器编程当中,为了实现异步,经常性的需要回调函数,例如以下这段代码
function send($value) { $data = process($value); onReceive($data);}function onReceive($recv_value) { var_dump($recv_value);}function process($value) { return $value+1;}$send_value = 1;send($send_value);
实现的东西很简单,其实就是将send_value发送到远端,远端服务器对其进行加一操作后,发送回来,于是在onReceive中我们可以得到远端服务器的返回值recv_value。
但是这样的代码就会看上去比较支离破碎,尤其是在process当中再次进行远程过程调用的时候,会变得更加难以开发和维护。协程就是为了解决这样的问题,使得异步的代码看起来同步化。
下面就是使用php的yield完成代码调度的示例(如果想看懂这段代码,需要首先了解一下php 5.5的新特性generator和yield)
框架代码如下:
class CCoroutine { /** * * @var Generator */ public $coroutine; /** * * @var miexed null or CCoroutine */ public $father; public function __construct($coroutine, $father = null) { $this->coroutine = $coroutine; $this->father = $father; }}class AsyncTask { public $data; public function __construct($data) { $this->data = $data; }}abstract class CoroutineScheduler { protected $coroutine = NULL; abstract function send_and_receive($value); public function run($data) { $co = $this->send_and_receive($data); $ccoroutine = new CCoroutine($co); $this->schedule($ccoroutine); } protected function schedule($ccoroutine) { $task = $ccoroutine->coroutine->current(); //如果当前值为空,表示这个$ccoroutine应该已经结束了 if (is_null($task)) { if (is_null($ccoroutine->father)) { //已经彻底调度结束了--一般是onRecieve方法运行到最后一步了 return; } else { //注意,如果运行到这个分支,则表示子生成器没有给父生成器传数据 //子生成器可能是通过引用传递来改变父生成器的变量值 //所以这个时候只要调度父生成器就可以了 $ccoroutine->father->coroutine->next(); $father = $ccoroutine->father; $this->schedule($father); unset($ccoroutine); } } else { if (is_object($task) && $task instanceof AsyncTask) { //当task是异步数据请求的时候,开始处理socket并且将进程熄火在这里 $this->dealTask($task, $ccoroutine); } elseif (is_object($task) && $task instanceof \Generator) { //当task是生成器时,表示当前生成器又有了子生成器的调用 $newcc = new CCoroutine($task, $ccoroutine); $this->schedule($newcc); } elseif ($ccoroutine->father != null) { //注意,如果运行到这个分支,则表示在子的生成器里调用了yield $str;这样的写法 //我们规定这种写法是在给父生成器传数据,所以当前生成器就会终止调用了转而去调度父生成器 $ccoroutine->father->coroutine->send($task); $father = $ccoroutine->father; $this->schedule($father); unset($ccoroutine); } } } protected function dealTask($task, $ccoroutine) { $this->coroutine = $ccoroutine; $this->send($task->data); } public function send($value) { $data = $this->process($value); $this->onReceive($data); } public function process($value) { return $value+1; } protected function onReceive($data) { $this->coroutine->coroutine->send($data); $this->schedule($this->coroutine); }}
框架将 send, onReceive等函数全部都封装好了,使得调用方的代码看起来可以是同步的代码
调用方代码如下:
//1. 需要去实现CoroutineScheduler的send_and_receive函数,主要是为了在里面拿到返回值class Solution extends CoroutineScheduler { public function send_and_receive($data) { $result = (yield new AsyncTask($data)); var_dump($result); }}//2. 在最外层去调用框架的代码,给出输入参数 $data$s = new Solution();$data = 1;$s->run($data);

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.
