1.在命令行进入项目根目录,然后用composer下载slim
composer require slim/slim "^3.0"
2.下载slim完成后,在php文件中引入require 'vendor/autoload.php';
获取 _GET 和 _POST 变量
$app->get('/', function (Request $req, Response $res, $args = []) {
$myvar1 = $req->getParam('myvar'); //检查 _GET 和 _POST [不遵循 PSR 7]
$myvar2 = $req->getParsedBody()['myvar']; //检查 _POST [遵循 PSR 7]
$myvar3 = $req->getQueryParams()['myvar']; //检查 _GET [遵循 PSR 7]
});
下面是一个完整的slim的小例子
<?php
use SlimHttpRequest as Request;
use SlimHttpResponse as Response;
require './vendor/autoload.php';
$app = new SlimApp;
$app->get('/hello', function (Request $request,Response $response){
$data=$request->getQueryParams();
var_dump($data);
//$response->getBody()->write("Hello");
});
$app->post('/mypost/test',function (Request $request,Response $response){
$data=$request->getParsedBody();
var_dump($data);
//$jsondata = $response->withJson(array('mypost'));
//return $jsondata;
});
//写一个中间件
$mid=function ($request, $response, $next) {
$response->getBody()->write('BEFORE');
$response = $next($request, $response);
$response->getBody()->write('AFTER');
return $response;
};
//写一个分组
$app->group('/api/service',function() use ($app){
$this->get('/myget',function (Request $request,Response $response){
$data=$request->getQueryParams();
var_dump($data);
});
$this->post('/mypost',function (Request $request,Response $response){
$data=$request->getParsedBody();
var_dump($data);
});
})->add($mid);
$app->run();
?>