介紹EasySwoole安裝使用

介紹EasySwoole安裝使用

EasySwoole

EasySwoole 是一款基于Swoole Server 開發(fā)的常駐內(nèi)存型的分布式PHP框架,專為API而生,擺脫傳統(tǒng)PHP運行模式在進程喚起和文件加載上帶來的性能損失。 EasySwoole 高度封裝了 Swoole Server 而依舊維持 Swoole Server 原有特性,支持同時混合監(jiān)聽HTTP、自定義TCP、UDP協(xié)議,讓開發(fā)者以最低的學習成本和精力編寫出多進程,可異步,高可用的應(yīng)用服務(wù)

推薦(免費):swoole

安裝

  • 保證 PHP 版本大于等于 7.1
  • 保證 Swoole 拓展版本大于等于 4.4.15
  • 需要 pcntl 拓展的任意版本
  • 使用 Linux / FreeBSD / MacOS 這三類操作系統(tǒng)
  • 使用 Composer 作為依賴管理工具

composer require easyswoole/easyswoole=3.x php vendor/easyswoole/easyswoole/bin/easyswoole install

  • 新版的easyswoole安裝會默認提供App命名空間,還有index控制器
  • 在這里面需要填寫n,不需要覆蓋,已經(jīng)有的 EasySwooleEvent.php,index.php dev.php produce.php
  • 當提示exec函數(shù)被禁用時,請自己手動執(zhí)行 composer dump-autoload 命令更新命名空間

進入項目根目錄執(zhí)行程序,項目執(zhí)行成功,訪問頁面

php easyswoole start
介紹EasySwoole安裝使用

介紹EasySwoole安裝使用

HTTP

HttpController為控制器根目錄,訪問會根據(jù)url自動映射到此目錄的控制器中,Index作為默認控制器,index為默認方法
介紹EasySwoole安裝使用

訪問http://192.168.88.16:9501地址為默認訪問到index.php控制器中index方法,即http://192.168.88.16:9501/index/index地址與tp框架的訪問相類似

  • 我們在index控制器中新建一個hello方法,打印hello world,重新啟動項目,訪問http://192.168.88.16:9501/hello和http://192.168.88.16:9501/index/hello頁面都會打印hello world
<?phpnamespace AppHttpController;use EasySwooleHttpAbstractInterfaceController;class Index extends Controller{  public function hello(){         $this->response()->write('hello world');     }      public function index()     {         $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/welcome.html';         if(!is_file($file)){             $file = EASYSWOOLE_ROOT.'/src/Resource/Http/welcome.html';//歡迎頁面         }         $this->response()->write(file_get_contents($file));     }      protected function actionNotFound(?string $action)     {         $this->response()->withStatus(404);         $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/404.html';         if(!is_file($file)){             $file = EASYSWOOLE_ROOT.'/src/Resource/Http/404.html';         }         $this->response()->write(file_get_contents($file));     }}

介紹EasySwoole安裝使用

WebSocket

WebSocket協(xié)議在傳統(tǒng)的phpweb框架就不適用了,在php中基本就使用workerman和swoole去解決這種場景,在easyswoole框架即是swoole的封裝

  • 在dev.php配置文件,將服務(wù)類型SERVER_TYPE修改為EASYSWOOLE_WEB_SOCKET_SERVER,進行WebSocket通訊,EasySwooleEvent.php文件中,新增主服務(wù)增加onMessage事件監(jiān)聽消息
<?phpnamespace EasySwooleEasySwoole;use EasySwooleEasySwooleSwooleEventRegister;use EasySwooleEasySwooleAbstractInterfaceEvent;use EasySwooleHttpRequest;use EasySwooleHttpResponse;class EasySwooleEvent implements Event{      public static function initialize()     {         // TODO: Implement initialize() method.         date_default_timezone_set('Asia/Shanghai');     }      public static function mainServerCreate(EventRegister $register)     {         // TODO: Implement mainServerCreate() method.         $register->set(EventRegister::onMessage,function (swoole_websocket_server $server, swoole_websocket_frame $frame){             var_dump($frame);         });     }      public static function onRequest(Request $request, Response $response): bool    {         // TODO: Implement onRequest() method.         return true;     }      public static function afterRequest(Request $request, Response $response): void    {         // TODO: Implement afterAction() method.     }}
  • 使用easyswoole的測試工具進行連接測試
    介紹EasySwoole安裝使用
    介紹EasySwoole安裝使用

WebSocket控制器

在WebSocket,一般都是在一個onmessage中寫響應(yīng)代碼,業(yè)務(wù)復雜的情況下一個方法中非常的冗長,easyswoole提供一種類似控制器方式的寫法,這里已官方的例子為例:

  • 安裝拓展包

composer require easyswoole/socket

dev.php,修改SERVER_TYPE為:

‘SERVER_TYPE’ => EASYSWOOLE_WEB_SOCKET_SERVER,

注冊服務(wù):

public static function mainServerCreate(EventRegister $register): void{     /**      * **************** websocket控制器 **********************      */     // 創(chuàng)建一個 Dispatcher 配置     $conf = new EasySwooleSocketConfig();     // 設(shè)置 Dispatcher 為 WebSocket 模式     $conf->setType(EasySwooleSocketConfig::WEB_SOCKET);     // 設(shè)置解析器對象     $conf->setParser(new WebSocketParser());     // 創(chuàng)建 Dispatcher 對象 并注入 config 對象     $dispatch = new Dispatcher($conf);     // 給server 注冊相關(guān)事件 在 WebSocket 模式下  on message 事件必須注冊 并且交給 Dispatcher 對象處理     $register->set(EventRegister::onMessage, function (swoole_websocket_server $server, swoole_websocket_frame $frame) use ($dispatch) {         $dispatch->dispatch($server, $frame->data, $frame);     });}

創(chuàng)建App/WebSocket/WebSocketParser.php文件

namespace AppWebSocket;use EasySwooleSocketAbstractInterfaceParserInterface;use EasySwooleSocketClientWebSocket;use EasySwooleSocketBeanCaller;use EasySwooleSocketBeanResponse;/**  * Class WebSocketParser  *  * 此類是自定義的 websocket 消息解析器  * 此處使用的設(shè)計是使用 json string 作為消息格式  * 當客戶端消息到達服務(wù)端時,會調(diào)用 decode 方法進行消息解析  * 會將 websocket 消息 轉(zhuǎn)成具體的 Class -> Action 調(diào)用 并且將參數(shù)注入  *  * @package AppWebSocket  */class WebSocketParser implements ParserInterface{     /**      * decode      * @param  string         $raw    客戶端原始消息      * @param  WebSocket      $client WebSocket Client 對象      * @return Caller         Socket  調(diào)用對象      */     public function decode($raw, $client) : ? Caller    {         // 解析 客戶端原始消息         $data = json_decode($raw, true);         if (!is_array($data)) {             echo "decode message error!  ";             return null;         }          // new 調(diào)用者對象         $caller =  new Caller();         /**          * 設(shè)置被調(diào)用的類 這里會將ws消息中的 class 參數(shù)解析為具體想訪問的控制器          * 如果更喜歡 event 方式 可以自定義 event 和具體的類的 map 即可          * 注 目前 easyswoole 3.0.4 版本及以下 不支持直接傳遞 class string 可以通過這種方式          */         $class = 'AppWebSocket'. ucfirst($data['class'] ?? 'Index');         $caller->setControllerClass($class);          // 提供一個事件風格的寫法//         $eventMap = [//             'index' => Index::class//         ];//         $caller->setControllerClass($eventMap[$data['class']] ?? Index::class);          // 設(shè)置被調(diào)用的方法         $caller->setAction($data['action'] ?? 'index');         // 檢查是否存在args         if (!empty($data['content'])) {             // content 無法解析為array 時 返回 content => string 格式             $args = is_array($data['content']) ? $data['content'] : ['content' => $data['content']];         }          // 設(shè)置被調(diào)用的Args         $caller->setArgs($args ?? []);         return $caller;     }     /**      * encode      * @param  Response     $response Socket Response 對象      * @param  WebSocket    $client   WebSocket Client 對象      * @return string             發(fā)送給客戶端的消息      */     public function encode(Response $response, $client) : ? string    {         /**          * 這里返回響應(yīng)給客戶端的信息          * 這里應(yīng)當只做統(tǒng)一的encode操作 具體的狀態(tài)等應(yīng)當由 Controller處理          */         return $response->getMessage();     }}

創(chuàng)建App/WebSocket/Index.php文件

composer require easyswoole/task

<?php/**  * Created by PhpStorm.  * User: Apple  * Date: 2018/11/1 0001  * Time: 14:42  */namespace AppWebSocket;use EasySwooleEasySwooleServerManager;use EasySwooleEasySwooleTaskTaskManager;use EasySwooleSocketAbstractInterfaceController;/**  * Class Index  *  * 此類是默認的 websocket 消息解析后訪問的 控制器  *  * @package AppWebSocket  */class Index extends Controller{     function hello()     {         $this->response()->setMessage('call hello with arg:'. json_encode($this->caller()->getArgs()));     }      public function who(){         $this->response()->setMessage('your fd is '. $this->caller()->getClient()->getFd());     }      function delay()     {         $this->response()->setMessage('this is delay action');         $client = $this->caller()->getClient();          // 異步推送, 這里直接 use fd也是可以的         TaskManager::getInstance()->async(function () use ($client){             $server = ServerManager::getInstance()->getSwooleServer();             $i = 0;             while ($i < 5) {                 sleep(1);                 $server->push($client->getFd(),'push in http at '. date('H:i:s'));                 $i++;             }         });     }}
  • 用websocket測試工具進行測試,進行提交的json自動到相應(yīng)的控制器方法中進行處理
    介紹EasySwoole安裝使用

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊10 分享