在中间件中将GET更改为POST - SLIM Framework 3

时间:2018-05-13 21:48:39

标签: routes slim middleware slim-3

我正在使用SLIM FRAMEWORK 3处理Rest API,我需要检查GET调用是否在Middleware中返回特定数据。如果没有返回数据,我需要先使用POST方法进行新调用,然后在API中写入数据,然后继续使用$ next()。

我尝试了withRedirect(),但似乎只适用于GET。有没有办法做到这一点?感谢。

<?php

$app->add(function($req, $res, $next){
$uri = $req->getUri()->getPath();

//get query_string params
$params = $req->getUri()->getQuery();
parse_str($params, $args);

//check if is desired route...
if($req->isGet() && isset($args['name']) && isset($args['borndate']) && $uri == 'api/v1/example'){
    global $app;

    //try to get data from DB 
    $dados_mapa = (new App\Models\MyExampleModel())->get()
            ->where('name', '=', $args['name'])
            ->where('borndate', '=', $args['borndate'])
            ->first();

    //check data
    if(isset($dados_mapa->id))
    {
        //data exists, continue
        return $next($req, $res);

    }else{

        //no data, I need to do a POST call here...
        $new_post_uri = 'api/v1/example';

        doPostHere($new_post_uri); ////how to make this POST?

        //continue with the first call
        return $next($req, $res);

    }

  }

});

1 个答案:

答案 0 :(得分:3)

要回答您的问题,请使用Guzzle执行POST请求,因为您希望执行新的HTTP调用,而Guzzle是PHP的一个非常好的HTTP客户端。

但是,请注意,这是一种特别糟糕的模式,您不应该这样做。 GET不应该有副作用,创建新数据肯定是副作用!

如果数据不存在,更好的模式是返回4xx错误,然后让客户端执行POST请求来创建它。