3 Star 8 Fork 2

sofical / restphp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
EPL-1.0

欢迎了解RestPHP,当前版本为2.0。

示例工程:https://gitee.com/sofical/dns-manager

RestPHP的特点

支持路径参数,如:/users/{userId} 或 /users/{userId}/orders/{orderId}

支持各种HTTP Method,支持Form表单、json、Xml的报文请求

支持多语言设置

支持表单注解验证

安装教程

  1. 使用submodule clone 本项目到您的项目的插件目录中,如:restphp

  2. 配置URL重新规则,将所有请求地址重写到上一步的程序入口文件。如,Nginx重写配置:

location / {
    index  index.php;
    if (!-e $request_filename) {            
        rewrite ^/(.*)$ /index.php?$1 last;                
    }            
}
  1. 项目配置文件,必要内容为:
//RESTPHP 相关配置
//版本号
define('REST_PHP_VERSION', '2.0');
//lib目录,此目录下的包可自动加载
define('DIR_LIB', 'lib');
//RestPHP程序目录
define('DIR_RESTPHP', DIR_LIB . DIRECTORY_SEPARATOR . 'restphp');
//路由文件生成目录
define('DIR_BUILD_TARGET', 'runtime/target');
//HTTP version
define('HTTP_VERSION', '1.1');
//默认接收报文类型
define('CONTENT_TYPE', 'application/json');
//系统时间,秒
define('SYS_TIME', time());
//系统时间,毫秒
define('SYS_MICRO_TIME', microtime(true));


//引入框架
require(DIR_RESTPHP . '/Rest.php');

//程序入口
\restphp\Rest::run();
  1. 构建入口配置,必要内容为:
//版本号
define('REST_PHP_VERSION', '2.0');
//lib目录,此目录下的包可自动加载
define('DIR_LIB', 'lib');
//RestPHP程序目录
define('DIR_RESTPHP', DIR_LIB . DIRECTORY_SEPARATOR . 'restphp');
//构建时需要扫描的目录
define('DIR_BUILD', 'com');
//路由文件生成目录
define('DIR_BUILD_TARGET', 'runtime/target');

//引入框架
require(DIR_RESTPHP . '/Rest.php');

//构建程序入口
\restphp\Rest::build();

示例项目:https://gitee.com/sofical/dns-manager

使用说明

文件加载

文件支持自动加载,不需要在逻辑代码中使用require或include。其中自动加载的区域分为了两块区域。

1、项目代码区,即 DIR_BUILD 下的项目文件。

2、lib区,即DIR_LIB下的文件。lib区一般用于第三方引用插件代码。

文件加载机制是通过命名空间和类名进行自动查询匹配,因此 类名需要和文件名保持一致

路由编写

使用注解@RequestMapping,参数:value、method

value 在class和function中都有效,值可以是一个或多,一个时,可以直接写为:value="/index.html"。多个时,应该写为:value=["/", "/index.html", "/index"]

method HTTP谓词(方法),即:GET、POST、PUT、DELETE、PATCH等,不区分大小写,建议使用大写。

完整示例:

/**
 * 首页路由.
 * @RequestMapping("")
 */
class IndexController {
    /**
     * 首页.
     * @RequestMapping(value=["/", "/index.html", "/index"], method="GET")
     */
    public function index() {
        // put your logic here
        echo "hello moto!";
    }
}
常用传参获取
路径参数

路径参数使用RestHttpRequest::getPathValue()方法获取。注:多路由不支持路径参数。

访问地址/users/97,获取用户ID:97

/**
 * @RequestMapping("/users")
 */
class UserController {
    /**
     * @RequestMapping(value="/{userId}", method="GET")
     */
    public function userInfo() {
        $userId = RestHttpRequest::getGet("userId");
        echo $userId;
    }
}
Query参数

Query参数使用RestHttpRequest::getGet() 或 RestHttpRequest::getParameterAsObject() 获取;使用 RestHttpRequeste::getPageParam() 获取分页对象。

其中RestHttpRequest::getGet() 用于获取单个路径参数,RestHttpRequest::getParameterAsObject() 用于以对象的形式获取一个或多个参数。

1.RestHttpRequest::getGet()应用举例

访问地址/users?name=张,获取name参数值:

/**
 * @RequestMapping("/users")
 */
class UserController {
    /**
     * @RequestMapping(value="", method="GET")
     */
    public function userList() {
        $name = RestHttpRequest::getGet("name");
        echo $name;
    }
}

2.RestHttpRequest::getParameterAsObject()应用举例

访问地址/users?name=张&mobile=1360000,获取name和mobile的查询对象

final class queryForm {
    private $_name;
    private $_mobile;
    public function getName() {
        return $this->_name;
    }
    public function setName($name) {
        $this-_name = $name;
    }
    public function getMobile() {
        return $this->_mobile;
    }
    public function setMobile($mobile) {
        $this-_mobile = $mobile;
    }
}

/**
 * @RequestMapping("/users")
 */
class UserController {
    /**
     * @RequestMapping(value="", method="GET")
     */
    public function userList() {
        $queryForm = RestHttpRequest::getParameterAsObject(new queryForm());
        var_export($queryForm);
    }
}
Body参数

Body 参数使用 RestHttpRequest::getBody() 获取。

应用举例,获取body内容:{"username":"小红","mobile":"13800000000","age":"18"}

final class userForm {
    private $_name;
    private $_mobile;
    private $_age;
    public function getName() {
        return $this->_name;
    }
    public function setName($name) {
        $this-_name = $name;
    }
    public function getMobile() {
        return $this->_mobile;
    }
    public function setMobile($mobile) {
        $this-_mobile = $mobile;
    }
    public function getAge() {
        return $this->_age;
    }
    public function setAget($age) {
        $this->_age = $age;
    }
}


/**
 * @RequestMapping("/users")
 */
class UserController {
    /**
     * @RequestMapping(value="", method="POST")
     */
    public function newUser() {
        //获取为对象
        $userForm = RestHttpRequest::getBody(new userForm());
        var_export($userForm);
        //获取为数组
        $arrUser = RestHttpRequest::getBody();
        var_dump($arrUser);
    }
}
数据验证

框架提供了以下注解表单验:

@length(min=最小长度,max=最大长度,message=错误提示)

@notnull(message=错误提示)

@mobile(message=错误提示)

@email(message=错误提示)

@domain(message=错误提示)

@date(format=日期格式,message=错误提示)

@range(min=最小长度,max=最大长度,message=错误提示)

@int(min=最小长度,max=最大长度,message=错误提示)

@ipv4(message=错误提示)

@ipv6(message=错误提示)

@inArray(value=[可选值1|可选值2],message=错误提示)

@notEmpty(message=错误提示)

@customer(method=自定义校验方法,message=错误提示)

使用示例:

<?php
namespace classes\controller\api\vo;

/**
 * Class MessageVo
 * @package classes\controller\api\vo
 */
class MessageVo {
    /**
     * 客户名称.
     * @length(min=1,max=20,message=名字输入长度为1~20个字符)
     * @var string.
     */
    private $_name;

    /**
     * 感兴趣的产品.
     * @length(min=1,max=50,message=感兴趣的产品输入长度为1-50个字符)
     * @var string
     */
    private $_product;

    /**
     * 手机号码.
     * @mobile(message=手机号不正确)
     * @var string
     */
    private $_mobile;

    /**
     * 更多说明
     * @length(max=255,message=更多说明长度不能超过255字)
     * @var string
     */
    private $_more;

    /**
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->_name = $name;
    }

    /**
     * @return string
     */
    public function getProduct()
    {
        return $this->_product;
    }

    /**
     * @param string $product
     */
    public function setProduct($product)
    {
        $this->_product = $product;
    }

    /**
     * @return string
     */
    public function getMobile()
    {
        return $this->_mobile;
    }

    /**
     * @param string $mobile
     */
    public function setMobile($mobile)
    {
        $this->_mobile = $mobile;
    }

    /**
     * @return string
     */
    public function getMore()
    {
        return $this->_more;
    }

    /**
     * @param string $more
     */
    public function setMore($more)
    {
        $this->_more = $more;
    }


}

<?php
namespace classes\controller\api;

use classes\controller\api\vo\MessageVo;
use classes\service\CrmMessageService;
use restphp\http\RestHttpRequest;
use restphp\validate\RestValidate;

/**
 * Class MessagesController
 * @RequestMapping(value="/api/messages")
 * @package classes\controller\api
 */
class MessagesController {
    /**
     * 接收消息.
     * @RequestMapping(value="", method="POST")
     * @throws \ReflectionException
     */
    public function receiveMessage() {
        $message = RestHttpRequest::getRequestBody(new MessageVo(), true);

        CrmMessageService::saveMessage($message);
    }
}
数据响应

数据响应为开放自由式响应,无特殊固定规则和格式。

框架的RestHttpResponse类提供常用数据响应方法封状;RestTpl类提供了简单的模板引擎。

更多请参考:https://gitee.com/sofical/restphp-core/blob/master/README.md

Eclipse Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. "Contributor" means any person or entity that distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 3. REQUIREMENTS A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: a) it complies with the terms and conditions of this Agreement; and b) its license agreement: i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. When the Program is made available in source code form: a) it must be made available under this Agreement; and b) a copy of this Agreement must be included with each copy of the Program. Contributors may not remove or alter any copyright notices contained within the Program. Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.

简介

轻量PHP RESTFul 框架 展开 收起
PHP
EPL-1.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
PHP
1
https://gitee.com/sofical/restphp.git
git@gitee.com:sofical/restphp.git
sofical
restphp
restphp
master

搜索帮助

14c37bed 8189591 565d56ea 8189591