brownpaperbag / flush
友好的数据刷新库。适用于长轮询和僵尸请求。
1.0.0
2014-10-30 22:10 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-14 16:51:03 UTC
README
友好的数据刷新库。适用于长轮询和僵尸请求。作为 composer 包分发。
安装
composer require brownpaperbag/flush
用法
该库基本上构建了三个场景
- 长轮询请求;
- 具有套接字风格的长轮询请求;
- 僵尸请求;
在长轮询请求中的用法
<?php use BrownPaperBag\Flush; $flush = new Flush('application/json'); $flush->prepare(); do{ if(!$flush->signal()){ break; } else{ // Your commands here or conditions to break in some point... } } while(sleep(1) || true); $flush->json(array( 'command' => 'location.reload();' ));
在具有套接字风格的长轮询请求中的用法
<?php use BrownPaperBag\Flush; $flush = new Flush('application/json'); $flush->prepare(); do{ $message = rand(1, 10); if(!$flush->signal()){ break; } else if($message % 2){ // Any condition you want... $flush->json(array( 'success' => true, 'message' => $message )); } } while(sleep(1) || true);
以下是一个如何在客户端接收响应的示例
var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if(this.status == 200){ switch(this.readyState){ case this.LOADING: var data = this.responseText, length = data.length; data = data.slice(this.lastLength - length); data = data.trim(data); this.lastLength = length; if(data.length){ data = $.parseJSON(data); // Whatever you want to do with your new object. // You can use it to implement push notifications for example... console.log(data); } break; } } }; request.open('GET', '/api/notifications', true); request.send();
在僵尸请求中的用法
<?php use BrownPaperBag\Flush; // You could use new Flush('application/json', true) instead of commands bellow. // Just showing another way... $flush = new Flush(); $flush->setContentType('application/json'); // Optional $flush->setLimboEnabled(true); // Required for zombie requests // Doing whatever task that user must to wait... $flush->json(array( // If limbo is enabled Flush will prepare() automatically. 'message' => 'An awesome return message here...' )); // To prevent prepare(), for any reason, just pass an explicit false as second argument in json/data(). // From this moment you can execute any task in background like: render a PDF, send emails or fire some slow script. // Just avoid to create an infinite loop :)
许可证
MIT