【问题标题】:Organize Slim 3 API routes logic into functions将 Slim 3 API 路由逻辑组织成函数
【发布时间】:2020-01-09 10:36:17
【问题描述】:

我想构建 API 以便将路由组织与单独文件中的操作分开。

当前代码没有返回任何错误,但是参数没有正确收集。

有没有不需要classes__invoke的简单方法组织成函数?,应用程序不需要它。

public/index.php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

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

$app = new \Slim\App;

foreach (glob("../src/middleware/*.php") as $middleware) {
  require $middleware;
}

require '../src/routes/routes.php';

$app->run();

src/routes/routes.php

$app->group('/v1', function () use ($app) {
    $app->post('/register', 'registerParticipant');        
});

src/middleware/registerParticipant.php

require '../lib/qrlib/vendor/qrlib.php';

function registerParticipant($request, $response, $args) {

  // demo for testing
  $foo= $request->post('foo'); 

  echo "foo= ".$foo;

  // more app logic

}

【问题讨论】:

  • 你说的parameters are not collected correctly是指post参数吗?此代码确实会引发错误:Call to undefined method Slim\Http\Request::post()

标签: php routing middleware slim slim-3


【解决方案1】:

$foo= $request->getParam('foo'); 替换$foo= $request->post('foo'); 就行了。

src/middleware/registerParticipant.php

require '../lib/qrlib/vendor/qrlib.php';

function registerParticipant($request, $response, $args) {

  // demo for testing
  $foo= $request->getParam('foo'); 

  echo "foo= ".$foo;

  // more app logic

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多