将 Slim 3 API 路由逻辑组织成函数
Organize Slim 3 API routes logic into functions
我想构造 API 以便将路由组织与单独文件中的操作分开。
当前代码没有return任何错误,但参数没有正确收集。
有没有不需要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
}
用 $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
}
我想构造 API 以便将路由组织与单独文件中的操作分开。
当前代码没有return任何错误,但参数没有正确收集。
有没有不需要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
}
用 $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
}