【问题标题】:PHP Slim - using anonymous functions with a simple rest apiPHP Slim - 使用带有简单 rest api 的匿名函数
【发布时间】:2018-10-11 14:53:55
【问题描述】:

我创建了一个简单的 rest api 来处理一些 POST 数据。我想在发送响应之前添加一些功能来清理数据。

我是 Slim 和 PHP 的新手,所以不确定这是否可行/我正在使用“正确”的方法解决问题。

这是我目前的尝试(不起作用!)调用了中间件,但进程函数总是返回 NULL

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require __DIR__ . '/../vendor/autoload.php';

$app = new \Slim\App();


// add function to $app
$app->process = function ($request, $response, $next) use($app) {
    return 'process';
};

$process = $app->process;

// middleware
$mw = function ($request, $response, $next) {
    $response = $next($request, $response);   

    // should return string from above function
    $variable = $process

    $data = array('name' => $name, 'process' => $variable);
    $newResp = $response->withJson($data);
    return $newResp;
};


$app->post('/api/name', function (Request $request, Response $response, array $args) {
    $parsed= $request->getParsedBody();
    $response = $response->withStatus(200);
})->add($mw);

$app->run();

【问题讨论】:

    标签: php rest slim


    【解决方案1】:

    有几个问题:

    1. $app 添加了函数,结果为BadMethodCallException
    2. $app已经有一个方法叫做process
    3. $variable = $process 之后错过了;

    这段代码给出了你想要的结果:

    use \Psr\Http\Message\ServerRequestInterface as Request;
    use \Psr\Http\Message\ResponseInterface as Response;
    
    require __DIR__ . '/../vendor/autoload.php';
    
    // turn error logging on!
    $app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
    
    // your function
    $sanitize = function(){
      return 'process';
    };
    
    // middleware + pass function
    $mw = function ($request, $response, $next) use($sanitize) {
      $response = $next($request, $response);
    
      $variable = $sanitize(); // execute function
    
      $data = array('name' => $name, 'process' => $variable);
      $newResp = $response->withJson($data);
      return $newResp;
    };
    
    
    $app->get('/api/name', function (Request $request, Response $response, array $args) {
      $parsed= $request->getParsedBody();
      $response = $response->withStatus(200);
    })->add($mw);
    
    $app->run();  
    

    当您不需要使用其他中间件中的函数时,您可以简单地在中间件中定义函数,如下所示:

    // middleware
    $mw = function ($request, $response, $next) use($sanitize) {
      $response = $next($request, $response);
    
      // your function
      function sanitize(){
        return 'process';
      }
    
      $data = array('name' => $name, 'process' => sanitize());
      $newResp = $response->withJson($data);
      return $newResp;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多