使用slim3快速开发RESTful API

关于slim

在php的框架世界中,除了像symfony、laravel以及zend这样的全栈式的框架之外,还存在着一些微框架,比如基于symfony的silex,基于laravel的lumen,以及这篇博客中要讲到的slim框架,他们不像别的框架那样笨重,而且存在很多的配置项,大多数都是开箱即用,学习周期也很短,看看文档大多在半天内就能掌握它的基本用法。

关于restful

RESTful架构:
  (1)每一个URI代表一种资源;
  (2)客户端和服务器之间,传递这种资源的某种表现层;
  (3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”;
  (4)GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源。
RESTful误区:
(1)URI包含动词;
  (2)URI中加入版本号。
注;以上内容出自阮一峰博文:http://www.ruanyifeng.com/blog/2011/09/restful.html
关于restful只有粗浅的理解,后期读完相关书籍之后再做完善。

slim的安装

这里使用composer安装slim,在命令行下运行如下命令即可安装slim框架:

composer require slim/slim "^3.0"

如果使用的是apache服务器,创建.htaccess文件,内容如下:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

再创建index.php文件,内容如下:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';

$app = new \Slim\App;
$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write("Hello, world");

    return $response;
});
$app->run();

目前的目录结构如下所示:
使用slim3快速开发RESTful API

这时访问http://localhost/slim,即可看到页面上展现出的hello,world。

实战

这里使用这篇文章http://www.codediesel.com/php/create-a-quick-rest-api-using-slim-framework/
中提到的例子来实现一个RESTful API的例子。
创建学生表:

CREATE TABLE IF NOT EXISTS `students` (
  `student_id` int(10) NOT NULL auto_increment,
  `score` int(10) default '0',
  `first_name` varchar(50) default NULL,
  `last_name` varchar(50) default NULL,
  PRIMARY KEY  (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

这里我们手动新增了一条记录:
使用slim3快速开发RESTful API

相关代码如下:

$app->get('/score/{id}', function (Request $request, Response $response, $args) {
    try
    {
        $db = getDB();
        $sth = $db->prepare("SELECT * FROM students WHERE student_id = :id");
        $sth->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $sth->execute();
        $student = $sth->fetch(PDO::FETCH_ASSOC);

        if($student) {
            $response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
            $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => $student
                ]
            ));
        } else {
            $response = $response->withStatus(404)->withHeader('Content-type', 'application/json');
            $response->getBody()->write(json_encode(
                [
                    'status' => 404,
                    'error' => 'student could not be found',
                    'datas' => $student
                ]
            ));
        }
        return $response;
        $db = null;
    } catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});

获取数据库连接的相关代码如下:

function getDB()
{
    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "";
    $dbname = "test";

    $mysql_conn_string = "mysql:host=$dbhost;dbname=$dbname";
    $dbConnection = new PDO($mysql_conn_string, $dbuser, $dbpass);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbConnection;
}

此时通过curl访问http://localhost/slim/score/1,得到:
使用slim3快速开发RESTful API


  • 相关代码如下:
$app->put('/score/{id}', function(Request $request, Response $response, $args) {
    try
    {
        $putDatas = $request->getParsedBody();
        $db = getDB();
        $sth = $db->prepare("UPDATE students SET score = :score WHERE student_id = :id");

        $sth->bindParam(':score', $putDatas['score'], PDO::PARAM_INT);
        $sth->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $ret = $sth->execute();

        $response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => 'update successfully'
                ]
            )
        );
        return $response;
        $db = null;
    } catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});

此时通过curl访问http://localhost/slim/score/2,得到:
使用slim3快速开发RESTful API


  • 相关代码如下:
$app->delete('/score/{id}', function (Request $request, Response $response, $args) {
    try
    {
        $db = getDB();
        $sth = $db->prepare("DELETE FROM students WHERE student_id = :id");
        $sth->bindParam(':id', $args['id'], PDO::PARAM_INT);
        $sth->execute();

        $response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => 'delete successfully'
                ]
            )
        );
        return $response;
        $db = null;

    } catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }
});

此时通过curl访问http://localhost/slim/score/2,得到:
使用slim3快速开发RESTful API
- 增
相关代码如下:

$app->post('/score', function(Request $request, Response $response, $args) {
    $postDatas = $request->getParsedBody();
    try {
        $db = getDB();
        $sth = $db->prepare("INSERT INTO students (score, first_name, last_name) VALUES (:score, :firstName, :lastName)");
        $sth->bindParam(':score', $postDatas['score'], PDO::PARAM_INT);
        $sth->bindParam(':firstName', $postDatas['firstName'], PDO::PARAM_STR);
        $sth->bindParam(':lastName', $postDatas['lastName'], PDO::PARAM_STR);
        $sth->execute();

        $response = $response->withStatus(200)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
                [
                    'status' => 200,
                    'error' => '',
                    'datas' => 'insert successfully'
                ]
            )
        );
        return $response;
        $db = null;

    } catch(PDOException $e) {
        $response = $response->withStatus(500)->withHeader('Content-type', 'application/json');
        $response->getBody()->write(json_encode(
            [
                'status' => 500,
                'error' => $e->getMessage(),
                'datas' => ''
            ]
        ));
        return $response;
        $db = null;
    }

});

此时通过curl访问http://localhost/slim/score,得到:
使用slim3快速开发RESTful API

注:这篇博文只是做一个入门案例,示例代码有很多坏味道和不规范的地方。

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页