SlimPhp框架的使用(三)获取POST数据

我们在controller里面处理逻辑,很多时候都需要知道接口发送过来的数据参数,在Slim里处理数据很简单,

定义方法

定义一个方法,作为接口访问调用。需要写至少两个参数$request$response,如下:

public function say(Request $request, Response $response, $params)
    {
    }
  • $request
    请求发送的内容,里面带有请求时发送的数据,在移动平台,多是使用json进行数据的传递。

  • $response
    接口返回的内容,进行返回值的格式和值设置

获取POST的数据

$request->getParams()可以获取post的所有数据,是一个对象数组。
$request->getParam('key','default')获取post的指定key对应的值,如果没有则返回default的值。

设置返回值

通过$response我们可以很方便的设置返回数据,例如json格式的数据。 $response->withJson($data, $status = null, $encodingOptions = 0)设置json的返回值,$data传递一个array数组。例如在方法最后写上 return $response->withJson($data);,返回data的数组的json字符串。

注意

编写完controller之后访问地址如果出现controller not found,可能是composer的问题,可以试试执行composer dump-autoload -o

Search by:GoogleBingBaidu