如何更改 SLIM 中的 api URL 属性(值)

问题描述 投票:0回答:2

我正在使用 slim 开发的 REST api 进行分页。 使用下面的API来获取当前的uri

(string) $request->getUri();

结果::http://localhost/slim/test_app/test/public/api/actions/?page=2

但是现在对于下一个请求,我需要将当前网址中的页码替换为(+1)即3,并传递返回给用户的数据,如下所示

{
"data":[
//data
]
"next": http://localhost/slim/test_app/test/public/api/actions/?page=3
}

替换页码的最佳方法是什么?我们有任何直接的 api 来替换属性吗?

php rest pagination slim
2个回答
0
投票

我添加了一个函数来合并属性,然后将查询绑定到 url,如下函数

private function merge_querystring($url = null,$query = null,$recursive = false)
    {
      if($url == null)
        return false;
      if($query == null)
        return $url;
      // split the url into it's components
      $url_components = parse_url($url);
      // if we have the query string but no query on the original url
      // just return the URL + query string
      if(empty($url_components['query']))
        return $url.'?'.ltrim($query,'?');
      // turn the url's query string into an array
      parse_str($url_components['query'],$original_query_string);
      // turn the query string into an array
      parse_str(parse_url($query,PHP_URL_QUERY),$merged_query_string);
      // merge the query string
      if($recursive == true)
        $merged_result = array_merge_recursive($original_query_string,$merged_query_string);
      else
        $merged_result = array_merge($original_query_string,$merged_query_string);
      // Find the original query string in the URL and replace it with the new one
      return str_replace($url_components['query'],http_build_query($merged_result),$url);
    }

我使用下面的方法将查询添加到网址

    $postQuery["page"]=$currentpage+1;
    //print_r($postQuery);
    //echo http_build_query($postQuery);
    $data["next"]= $this->merge_querystring($request->getUri(),"?".http_build_query($postQuery));   

0
投票

您可以通过字符串操作替换分页值。但您也可以使用 Slim 提供的功能。

实现

Slim\Http\Uri

Psr\Http\Message\UriInterface
类具有
withQuery()
方法,该方法将替换当前查询字符串。

它将返回克隆的

Slim\Http\Uri
实例,并替换其查询字符串。

$query = $request->getQueryParams();
$query['page'] = $query['page'] + 1;
$url = $request->getUri();
$nextUrl = $url->withQuery(http_build_query($query));
$data['next'] = (string) $nexUrl;
© www.soinside.com 2019 - 2024. All rights reserved.