资讯专栏INFORMATION COLUMN

Swoole 实现简单的路由

xiaowugui666 / 2124人阅读

摘要:封装請確認是否已安裝請編輯中通過本函數綁定路由綁定所有路由路由路由路由路由路由路由使用

封装 xserver.php:

[],"post"=>[],"put"=>[],"head"=>[],"delete"=>[]];

    /**
     * start
     * @param  string       $action
     * @param  closure      $callback
     */
    public function start() {
        parent::on("request", function($req, $res){
            $do = $this->initRequest($req, $res, $this); $req = $do["req"]; $res = $do["res"];

            if( isset($this->route[strtolower($req->server["request_method"])][$req->server["request_uri"]]) )
                return call_user_func_array(
                    $this->route[strtolower($req->server["request_method"])][$req->server["request_uri"]],
                    [$req, $res, $do["get"], $do["post"], $do["server"], $do["session"], $this->_GLOBAL_SESSION, $ip ]
                );

            else return call_user_func_array(
                $this->route["error"]["404"],
                [$req, $res, $do["get"], $do["post"], $do["server"], $do["session"], $this->_GLOBAL_SESSION, $ip ]
            );
        });

        parent::start();
    }

    /**
     * all,get,post,put,head,delete通過本函數綁定路由
     * @param string    $method
     * @param string    $path
     * @param closure   $callback
     */
    public function path($method, $path, $callback){
        $this->route[$method][$path] = $callback;
    }

    /**
     * 綁定所有路由
     * @param string    $path
     * @param closure   $callback
     */
    public function all($path, $callback){
        foreach (["get","post","head","put","delete"] as $method)
            $this->path($method,    $path, $callback);
    }

    /**
     * GET路由
     * @param string    $path
     * @param closure   $callback
     */
    public function get($path, $callback){
        $this->path("get", $path, $callback);
    }

    /**
     * POST路由
     * @param string    $path
     * @param closure   $callback
     */
    public function post($path, $callback){
        $this->path("post", $path, $callback);
    }

    /**
     * PUT路由
     * @param string    $path
     * @param closure   $callback
     */
    public function put($path, $callback){
        $this->path("put", $path, $callback);
    }

    /**
     * HEAD路由
     * @param string    $path
     * @param closure   $callback
     */
    public function head($path, $callback){
        $this->path("head", $path, $callback);
    }

    /**
     * DELETE路由
     * @param string    $path
     * @param closure   $callback
     */
    public function delete($path, $callback){
        $this->path("delete", $path, $callback);
    }

    /**
     * ERROR路由
     * @param string    $path
     * @param closure   $callback
     */
    public function error($path, $callback){
        $this->path("error", $path, $callback);
    }

    public function initRequest($req, $res) {
        if (!isset($req->server)) $req->server = [];
        if (!isset($req->get)) $req->get = [];
        if (!isset($req->post)) $req->post = [];

        if (isset($req->server["accept-encoding"]) && stripos($req->server["accept-encoding"], "gzip")) {
            $res->gzip(5);
        }

        if (!isset($req->cookie) || !isset($req->cookie["sid"]) || !$req->cookie["sid"]) {
            $req->cookie["sid"] = md5(password_hash(time() . mt_rand(100000, 999999), 1));
            @$res->cookie("sid", $req->cookie["sid"], time() + 60 * 60 * 24 * 365 * 10, "/", "", false, true);
        }
        $_SESS_ID = $req->cookie["sid"];
        if (!isset($this->_GLOBAL_SESSION[$_SESS_ID]) || !is_array($this->_GLOBAL_SESSION[$_SESS_ID])) {
            $this->_GLOBAL_SESSION[$_SESS_ID] = [];
        }
        $_SESSION = &$this->_GLOBAL_SESSION[$_SESS_ID];

        if (isset($req->header)) {
            isset($req->header["if-none-match"])                ? $req->server["if-none-match"]                     = $req->header["if-none-match"]                 : false;
            isset($req->header["if-modified-since"])            ? $req->server["if-modified-since"]                 = $req->header["if-modified-since"]             : false;
            isset($req->header["connection"])                   ? $req->server["connection"]                        = $req->header["connection"]                    : false;
            isset($req->header["accept"])                       ? $req->server["accept"]                            = $req->header["accept"]                        : false;
            isset($req->header["accept-encoding"])              ? $req->server["accept-encoding"]                   = $req->header["accept-encoding"]               : false;
            isset($req->header["accept-language"])              ? $req->server["accept-language"]                   = $req->header["accept-language"]               : false;
            isset($req->header["upgrade-insecure-requests"])    ? $req->server["upgrade-insecure-requests"]         = $req->header["upgrade-insecure-requests"]     : false;
            isset($req->header["cache-control"])                ? $req->server["cache-control"]                     = $req->header["cache-control"]                 : false;
            isset($req->header["pragma"])                       ? $req->server["pragma"]                            = $req->header["pragma"]                        : false;
            isset($req->header["referer"])                      ? $req->server["referer"]                           = $req->header["referer"]                       : false;
            isset($req->header["x-forwarded-for"])              ? $req->server["remote_addr"]                       = $req->header["x-forwarded-for"]               : false;
            stripos($req->server["remote_addr"], ",")           ? $req->server["remote_addr"]                       = stripos($req->server["remote_addr"],",")[0]   : false;
        }
        return ["req"=>$req, "res"=>$res, "session"=>$_SESSION, "server"=>$req->server, "get"=>$req->get, "post"=>$req->post];
    }
}

class BaseException extends Exception {
    var $data = [];
    function __construct($message, $code, $data = []) {
        if ($data == []) {
            $data = new stdClass();
        }

        $this->data = $data;
        parent::__construct($message, $code);
        return $this;
    }
    function getData() {
        return $this->data;
    }
}

class QueueException extends BaseException {}
class ApiException extends BaseException {}

使用: app.php

define("APP_PATH", dirname(__FILE__) . "/");
require_once APP_PATH."xserver.php";
$server = new XServer("0.0.0.0", 3155);
$server->get("/test/", function ($req, $res, $_X_GET, $_X_POST, $_X_SERVER, $_X_SESSION, $_X_GLOBAL, $ip) use ($server) {
    try {
        $res->end("TEST get");
        return;
    } catch (ApiException $e) {

    }
});
$server->post("/test/", function ($req, $res, $_X_GET, $_X_POST, $_X_SERVER, $_X_SESSION, $_X_GLOBAL, $ip) use ($server) {
    try {
        $res->end("TEST post");
        return;
    } catch (ApiException $e) {

    }
});
$server->all("/test/all/", function ($req, $res, $_X_GET, $_X_POST, $_X_SERVER, $_X_SESSION, $_X_GLOBAL, $ip) use ($server) {
    try {
        $res->end("TEST all");
        return;
    } catch (ApiException $e) {

    }
});
$server->start();

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/30408.html

相关文章

  • Swoft 源码解读

    摘要:官网源码解读号外号外欢迎大家我们开发组定了一个就线下聚一次的小目标里面的框架算是非常重的了这里的重先不具体到性能层面主要是框架的设计思想和框架集成的服务让框架可以既可以快速解决很多问题又可以轻松扩展中的框架有在应该无出其右了这次解读的源码 官网: https://www.swoft.org/源码解读: http://naotu.baidu.com/file/8... 号外号外, 欢迎大...

    weij 评论0 收藏0
  • 一个简单混合协议通讯列子,物联网和互联网通讯。

    摘要:初始化发送消息判断用户是否登录如果没有登录拒绝连接断开清除信息处理协议主要是方法,轮训获取消息。 这个列子主要讨论Tcp,WebSocket和http之间的通讯。长连接和长连接通讯,长连接和短连接通讯。其他协议同理可得 Tcp: 代表硬件设备 WebSocket: 代表客户端 http: 代表网页 本列子是基于one框架 (https://github.com/lizhicha...

    王军 评论0 收藏0
  • 一个极简基于swoole常驻内存框架

    摘要:于是打算做一个拥有非常好用的路由和又非常简单的框架。但也有一些自己的特色,例如支持自动化缓存自动化读写刷新保持与数据库同步,对外使用无感知。例如协议服务器地址远程的类不设置默认为当前类名其中类在框架里。 背景 在用过laravel框架,发现它的路由和数据库ORM确实非常好用,但是整体确实有点慢,执行到控制器大于需要耗时60ms左右。于是打算做一个拥有非常好用的路由和orm又非常简单的框...

    Steve_Wang_ 评论0 收藏0
  • IMI 基于 Swoole 开发协程 PHP 开发框架 常驻内存、协程异步非阻塞

    摘要:介绍是基于开发的协程开发框架,拥有常驻内存协程异步非阻塞等优点。宇润我在年开发并发布了第一个框架,一直维护使用至今,非常稳定,并且有文档。于是我走上了开发的不归路 showImg(https://segmentfault.com/img/bVbcxQH?w=340&h=160); 介绍 IMI 是基于 Swoole 开发的协程 PHP 开发框架,拥有常驻内存、协程异步非阻塞IO等优点。...

    airborne007 评论0 收藏0
  • Swoft 源码剖析 - Swoole和Swoft那些事 (Http/Rpc服务篇)

    摘要:和服务关系最密切的进程是中的进程组,绝大部分业务处理都在该进程中进行。随后触发一个事件各组件通过该事件进行配置文件加载路由注册。事件每个请求到来时仅仅会触发事件。服务器生命周期和服务基本一致,详情参考源码剖析功能实现 作者:bromine链接:https://www.jianshu.com/p/4c0...來源:简书著作权归作者所有,本文已获得作者授权转载,并对原文进行了重新的排版。S...

    张汉庆 评论0 收藏0

发表评论

0条评论

阅读需要支付1元查看
<