作为程序员一定要保持良好的睡眠,才能好编程

RestFul API 实现代码

发布时间:2018-04-26


使用火狐 RestClient 插件进行测试


curl -X POST -H 'Content-Type: application/json' -i 'http://localhost/restful/imooc-restful/my/index.php/users' --data '{"username":"james","password":"123"}'



实现接口:php代码

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24
 * Time: 23:25
 */

/*require_once __DIR__ . '/../handler/User.php';
require_once __DIR__ . '/../handler/Article.php';
require_once __DIR__ . '/../handler/MyHttpException.php';*/

class Restful{

    /**
     * @var 用户user模型类
     */
    private $_user;
    /**
     * @var新闻文章模型类
     */
    private $_article;

    /**
     * @var array 请求的方法
     */
    private $_requestMethod;

    private $_resourceName;

    private $_id;

    private $_allowResources=['users','articles'];

    /**
     * @var array 允许访问的方式
     */
    private $_allowReqeustMethod=['GET','POST','PUT','DELETE','OPTIONS'];

    /**
     * 定义常用的变量
     * @var array
     */
    private $_statusCodes=[
        100 => 'HTTP/1.1 100 Continue',
        101 => 'HTTP/1.1 101 Switching Protocols',
        200 => 'HTTP/1.1 200 OK',
        201 => 'HTTP/1.1 201 Created',
        202 => 'HTTP/1.1 202 Accepted',
        203 => 'HTTP/1.1 203 Non-Authoritative Information',
        204 => 'HTTP/1.1 204 No Content',
        205 => 'HTTP/1.1 205 Reset Content',
        206 => 'HTTP/1.1 206 Partial Content',
        300 => 'HTTP/1.1 300 Multiple Choices',
        301 => 'HTTP/1.1 301 Moved Permanently',
        302 => 'HTTP/1.1 302 Found',
        303 => 'HTTP/1.1 303 See Other',
        304 => 'HTTP/1.1 304 Not Modified',
        305 => 'HTTP/1.1 305 Use Proxy',
        307 => 'HTTP/1.1 307 Temporary Redirect',
        400 => 'HTTP/1.1 400 Bad Request',
        401 => 'HTTP/1.1 401 Unauthorized',
        402 => 'HTTP/1.1 402 Payment Required',
        403 => 'HTTP/1.1 403 Forbidden',
        404 => 'HTTP/1.1 404 Not Found',
        405 => 'HTTP/1.1 405 Method Not Allowed',
        406 => 'HTTP/1.1 406 Not Acceptable',
        407 => 'HTTP/1.1 407 Proxy Authentication Required',
        408 => 'HTTP/1.1 408 Request Time-out',
        409 => 'HTTP/1.1 409 Conflict',
        410 => 'HTTP/1.1 410 Gone',
        411 => 'HTTP/1.1 411 Length Required',
        412 => 'HTTP/1.1 412 Precondition Failed',
        413 => 'HTTP/1.1 413 Request Entity Too Large',
        414 => 'HTTP/1.1 414 Request-URI Too Large',
        415 => 'HTTP/1.1 415 Unsupported Media Type',
        416 => 'HTTP/1.1 416 Requested range not satisfiable',
        417 => 'HTTP/1.1 417 Expectation Failed',
        500 => 'HTTP/1.1 500 Internal Server Error',
        501 => 'HTTP/1.1 501 Not Implemented',
        502 => 'HTTP/1.1 502 Bad Gateway',
        503 => 'HTTP/1.1 503 Service Unavailable',
        504 => 'HTTP/1.1 504 Gateway Time-out',
        505 => 'HTTP/1.1 505 HTTP Version not supported',



    ];
    /**
     *
     */
    public function run(){
       try{
           $this->_setRequestMethod();
           $this->_setResource();

           switch($this->_resourceName){


               case "users":
                   $this->_json($this->usersHandler());
                   break;
               case "articles":
                   $this->requestAuth();
                   $this->_json($this->articlesHandler());
                   break;

           }


       }catch (Exception $e){
            $this->_json(['error'=>$e->getMessage()],$e->getCode());
       }
    }

    /**
     * @param $_user
     * @param $_article
     */
    function __construct($_user, $_article) {
        $this->_user = $_user;
        $this->_article = $_article;
    }

    private function _setRequestMethod()
    {
        $this->_requestMethod=$_SERVER['REQUEST_METHOD'];
        if(!in_array($this->_requestMethod,$this->_allowReqeustMethod)){
            throw new Exception("请求方法不被允许",405);
        }
    }

    private function _setResource(){
        $pathInfo=$_SERVER['PATH_INFO'];
        if(empty($pathInfo))  throw new Exception("请求连接地址错误",400);
        $pathInfo=trim($pathInfo,'/');
        $path_arr=explode("/",$pathInfo);
        $this->_resourceName=$path_arr[0];

        //判断 如果资源不在资源范围内,剖出异常 不被允许
        if(!in_array($this->_resourceName,$this->_allowResources)){
            throw new Exception("请求资源不被允许",400);
        }

        if(!empty($path_arr[1])){
            $this->_id=$path_arr[1];
        }
    }


    private function getBodyParams(){
        $raw=file_get_contents("php://input");
        if(empty($raw)){
            throw new Exception("请求参数错误",400);
        }
        //直接转化为数组
        return json_decode($raw,true);

    }

    private function _json($_arr,$code=200){
        header("Content-Type:application/json;charset=utf-8");
        if($code>0 && $code!=200 && $code!=204){
            header("Http/1.1 ".$code."  ".$this->_statusCodes[$code]);
        }
        $_arr['code']=$code;
        echo json_encode($_arr,JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * @throws Exception
     */
    private function usersHandler(){
        switch($this->_requestMethod){
            case "POST":
                $body=$this->getBodyParams();
                if(isset($body['type'])&& $body['type']==="login"){
                    //登录
                    return $this->userLogin($body['username'],$body['password']);
                }elseif(isset($body['type'])&& $body['type']==="register"){
                    //注册
                    return $this->userRegister($body['username'],$body['password']);
                }
                throw new MyHttpException(401,"不被权限范围内访问");
                break;
            case "GET":
                return $this->userView($this->_id);
                break;
        }

    }

    /*private function usersHandler(){

        if($this->_requestMethod!=="POST"){
            throw new Exception("请求方法错误",400);
        }

        $body=$this->getBodyParams();

        //进行判断如果有什么问题直接返回即可

        if(!isset($body['username']) || empty($body['username'])){
            throw new Exception("用户名不能为空",400);
        }
        if(!isset($body['password']) || empty($body['password'])){
            throw new Exception("密码不能为空",400);
        }

        file_put_contents("file.txt","注册信息:".implode(",",$body),FILE_APPEND);

        return ["message"=>"注册成功"];


    }*/

    private function articlesHandler(){

        switch($this->_requestMethod){
            case "POST":
                return $this->articleCreate();
                break;
            case "PUT":
                return $this->articleEdit();
                break;
            case "DELETE":
                return $this->articleDelete();
                break;
            case "GET":
                if(empty($this->_id)){
                    return $this->articleView();
                }else{
                    return $this->articleList();
                }
                break;
            default :
                throw new Exception("请求方法不被允许",403);
        }

    }

    /**
     * 创建文章
     */
    private function articleCreate(){
        $_res=file_put_contents("article.txt",microtime(true)."articleCreate.\n",FILE_APPEND);
        return ['res'=>$_res];
    }

    private function articleEdit(){
        $_res=file_put_contents("article.txt",microtime(true)."articleEdit.\n",FILE_APPEND);
        return ['res'=>$_res];
    }

    private function articleDelete(){
        $_res=file_put_contents("article.txt",microtime(true)."articleDelete\n",FILE_APPEND);
        return ['res'=>$_res];
    }

    private function articleView(){
        $_res=file_get_contents("article.txt");
        return ['res'=>$_res];
    }

    private function articleList(){
        $_res=file_get_contents("article.txt");
        return ['res'=>$_res];
    }

    private function userLogin($username, $password)
    {
        return $this->_user->login($username,$password);
    }

    /**
     * @param $username
     * @param $password
     */
    private function userRegister($username, $password)
    {
        return $this->_user->register($username,$password);
    }

    private function userView($_id)
    {
        return $this->_user->view($_id);
    }



    /**
     * 要求认证
     * @return bool|array
     * @throws MyHttpException
     *
     * 添加header头信息  Authorization   值 Basic  amFtZXM6MTIzNDU2
     *
     * base64 加密后的字符串  amFtZXM6MTIzNDU2
     *
     * 格式 username:123456
     *
     *
     *您无法使用 PHP_AUTH_* 变量,而只能使用 HTTP_AUTHORIZATION。例如,考虑如下代码:list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));。
     */
    private function requestAuth()
    {


        echo $_SERVER['PHP_AUTH_USER'];
        echo $_SERVER['PHP_AUTH_PW'];
        if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW']))
        {
            try
            {
                $user = $this->_user->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
                return $user;
            }
            catch (MyHttpException $e)
            {
                if ($e->getStatusCode() != 422)
                {
                    throw $e;
                }
            }
        }
        header("WWW-Authenticate:Basic realm='Private'");
        header('HTTP/1.0 401 Unauthorized');
        print "You are unauthorized to enter this area.";
        exit(0);
    }





}


class MyHttpException extends Exception{
    private $statusCode;
    public function __construct($statusCode,$_message,$_code=0,$exception=null){
        parent::__construct($_message,$_code,$exception);
        $this->statusCode=$statusCode;
    }
    public function getStatusCode(){
        return $this->statusCode;
    }
}

class MyPdo extends \Pdo{

    public function __construct($host,$username,$password,$dbname){
        $dsn="mysql:host={$host};dbname={$dbname}";
        $params=[
            PDO::ATTR_EMULATE_PREPARES=>false
        ];
        parent::__construct($dsn,$username,$password,$params);
    }
}



class User{

    private $db=null;
    private $salt='songsong';

    public function __construct($_db){
        $this->db=$_db;

    }

    public function view($userid){

        if(empty($userid) || !intval($userid)){
            throw new MyHttpException(422,"用户ID不能为空");
        }

        $sql="select * from user where id=:id limit 1";
        $stmt=$this->db->prepare($sql);
        $stmt->bindParam(":id",$userid);
        $stmt->execute();
        $_res=$stmt->fetch(PDO::FETCH_ASSOC);
        if(!$_res){
            throw new MyHttpException(422,"此ID用户飘到外星去了");
        }
        unset($_res['password']);
        return $_res;
    }

    public function login($username,$password){

        if(empty($username)){
            throw new MyHttpException(422,"用户名不能为空");
        }

        if(empty($password)){
            throw new MyHttpException(422,"密码不能为空");
        }

        $sql="select id,username,createtime from user where username=:username and password=:password limit 1";
        $password=md5(md5($password.$this->salt));
        $stmt=$this->db->prepare($sql);
        $stmt->bindParam(":username",$username);
        $stmt->bindParam(":password",$password);
        $stmt->execute();
        $_res=$stmt->fetch(PDO::FETCH_ASSOC);
        if(!$_res){
            throw new MyHttpException(422,"用户名或密码错误");
        }
        return $_res;
    }

    public function register($username,$password){

        //判断
        if(empty($username)){
            throw new MyHttpException(422,"用户名不能为空");
        }

        if(empty($password)){
            throw new MyHttpException(422,"密码不能为空");
        }
        $password=md5(md5($password.$this->salt));
        $createtime=time();
        $sql="INSERT INTO user(`username`,`password`,`createtime`)VALUES(:username,:password,:createtime)";

        if($this->userExists($username)){
            throw new MyHttpException(422,"此用户已经存在了");
        }
        //判断数据库是否存在,如果存在就返回

        $stmt=$this->db->prepare($sql);
        $stmt->bindParam(":username",$username);
        $stmt->bindParam(":password",$password);
        $stmt->bindParam(":createtime",$createtime);
        if(!$stmt->execute()){
            throw new MyHttpException(500,"数据库服务器错误");
        }
        return ["userid"=> $this->db->lastInsertId(),"username"=>$username,"createtime"=>date("Y-m-d H:i:s",$createtime)];
    }
    public function userExists($username){
        $sql="SELECT id FROM user WHERE username=:username LIMIT 1";
        $stmt=$this->db->prepare($sql);
        $stmt->bindParam(":username",$username);
        $stmt->execute();
        if($stmt->fetch(PDO::FETCH_ASSOC)){
            return true;
        }
        return false;
    }
}



/*try{


    //$_data=$user->register("james","123456");
    //$_data=$user->login("james","123456");
    $_data=$user->view(1);
    echo json_encode($_data,JSON_UNESCAPED_UNICODE);


}catch(MyHttpException $e){

    echo "自定义的异常";
    echo $e->getStatusCode();
    echo $e->getMessage();

}catch(\Exception $e){
    echo "系统异常";
    echo $e->getMessage();
    echo $e->getCode();
}




curl -X POST -H 'Content-Type: application/json' -i 'http://localhost/restful/imooc-restful/my/index.php/users/1' --data '{"username":"song","password":"123","type":"register"}'

curl -X POST -H 'Content-Type: application/json' -i 'http://localhost/restful/imooc-restful/my/index.php/users/1' --data '{"username":"song","password":"123","type":"login"}'



*/









$pdo=new MyPdo("127.0.0.1","root","song","test");

$user=new User($pdo);

$restful=new Restful($user,null);
$restful->run();





db数据库

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` char(32) NOT NULL,
  `createtime` int(11) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8




2开头 (请求成功)表示成功处理了请求的状态代码。

200   (成功)  服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。 
201   (已创建)  请求成功并且服务器创建了新的资源。 
202   (已接受)  服务器已接受请求,但尚未处理。 
203   (非授权信息)  服务器已成功处理了请求,但返回的信息可能来自另一来源。 
204   (无内容)  服务器成功处理了请求,但没有返回任何内容。 
205   (重置内容) 服务器成功处理了请求,但没有返回任何内容。
206   (部分内容)  服务器成功处理了部分 GET 请求。

3开头 (请求被重定向)表示要完成请求,需要进一步操作。 通常,这些状态代码用来重定向。

300   (多种选择)  针对请求,服务器可执行多种操作。 服务器可根据请求者 (user agent) 选择一项操作,或提供操作列表供请求者选择。 
301   (永久移动)  请求的网页已永久移动到新位置。 服务器返回此响应(对 GET 或 HEAD 请求的响应)时,会自动将请求者转到新位置。
302   (临时移动)  服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求。
303   (查看其他位置) 请求者应当对不同的位置使用单独的 GET 请求来检索响应时,服务器返回此代码。
304   (未修改) 自从上次请求后,请求的网页未修改过。 服务器返回此响应时,不会返回网页内容。 
305   (使用代理) 请求者只能使用代理访问请求的网页。 如果服务器返回此响应,还表示请求者应使用代理。 
307   (临时重定向)  服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求。

4开头 (请求错误)这些状态代码表示请求可能出错,妨碍了服务器的处理。

400   (错误请求) 服务器不理解请求的语法。 
401   (未授权) 请求要求身份验证。 对于需要登录的网页,服务器可能返回此响应。 
403   (禁止) 服务器拒绝请求。
404   (未找到) 服务器找不到请求的网页。
405   (方法禁用) 禁用请求中指定的方法。 
406   (不接受) 无法使用请求的内容特性响应请求的网页。 
407   (需要代理授权) 此状态代码与 401(未授权)类似,但指定请求者应当授权使用代理。
408   (请求超时)  服务器等候请求时发生超时。 
409   (冲突)  服务器在完成请求时发生冲突。 服务器必须在响应中包含有关冲突的信息。 
410   (已删除)  如果请求的资源已永久删除,服务器就会返回此响应。 
411   (需要有效长度) 服务器不接受不含有效内容长度标头字段的请求。 
412   (未满足前提条件) 服务器未满足请求者在请求中设置的其中一个前提条件。 
413   (请求实体过大) 服务器无法处理请求,因为请求实体过大,超出服务器的处理能力。 
414   (请求的 URI 过长) 请求的 URI(通常为网址)过长,服务器无法处理。 
415   (不支持的媒体类型) 请求的格式不受请求页面的支持。 
416   (请求范围不符合要求) 如果页面无法提供请求的范围,则服务器会返回此状态代码。 
417   (未满足期望值) 服务器未满足"期望"请求标头字段的要求。

5开头(服务器错误)这些状态代码表示服务器在尝试处理请求时发生内部错误。 这些错误可能是服务器本身的错误,而不是请求出错。

500   (服务器内部错误)  服务器遇到错误,无法完成请求。 
501   (尚未实施) 服务器不具备完成请求的功能。 例如,服务器无法识别请求方法时可能会返回此代码。 
502   (错误网关) 服务器作为网关或代理,从上游服务器收到无效响应。 
503   (服务不可用) 服务器目前无法使用(由于超载或停机维护)。 通常,这只是暂时状态。 
504   (网关超时)  服务器作为网关或代理,但是没有及时从上游服务器收到请求。 
505   (HTTP 版本不受支持) 服务器不支持请求中所用的 HTTP 协议版本。