1. 程式人生 > >[轉] 使用slim3快速開發RESTful API

[轉] 使用slim3快速開發RESTful API

本文轉自:https://blog.csdn.net/u011250882/article/details/50101599

版權宣告:本文為博主原創文章,轉載請註明出處和作者名,尊重別人也是尊重自己 https://blog.csdn.net/u011250882/article/details/50101599
關於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"
1
如果使用的是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();

目前的目錄結構如下所示:


這時訪問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;

這裡我們手動新增了一條記錄:



相關程式碼如下:

$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,得到:



相關程式碼如下:
$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,得到:



相關程式碼如下:
$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,得到:

- 增
相關程式碼如下:

$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,得到:


注:這篇博文只是做一個入門案例,示例程式碼有很多壞味道和不規範的地方。
---------------------
作者:dongxie548
來源:CSDN
原文:https://blog.csdn.net/u011250882/article/details/50101599
版權宣告:本文為博主原創文章,轉載請附上博文連結!