Slim 4 - Uncaught TypeError: Argument 1 passed to {closure}() must be an instance of RouterCollectorProxy

Slim 4 - Uncaught TypeError: Argument 1 passed to {closure}() must be an instance of RouterCollectorProxy

我正在按照 slim 4 的指南创建路由组,但是当我尝试测试已部署的 heroku 应用程序时出现此错误:

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to {closure}() must be an instance of RouterCollectorProxy, instance of Slim\Routing\RouteCollectorProxy given, called in /app/vendor/slim/slim/Slim/Routing/RouteGroup.php on line 75 and defined in /app/index.php:17

我的代码有什么问题?也许我遗漏了什么?

<?php 

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Updater\DefinitionUpdater;

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

$app = AppFactory::create();

$app->get('/',function(Request $request, Response $response, $args){
    $response->getBody()->write('Hello world!');
    return $response;
});
$app->group('/api/v1', function(RouteCollectorProxy $group){
/**/
$app->get('/list', function(Request $request, Response $response, $args){
    $list = DefinitionUpdater::updateList();
    $response->getBody()->write( json_encode($list, JSON_UNESCAPED_SLASHES) );
    return $response->withHeader( 'Content-Type', 'application/json' );
})->setName('privacy');
/**/
$app->get('/privacy', function(Request $request, Response $response, $args){
    $privacy = DefinitionUpdater::updatePrivacy();
    $response->getBody()->write( json_encode($privacy, JSON_UNESCAPED_SLASHES) );
    return $response->withHeader( 'Content-Type', 'application/json' );
})->setName('privacy');
/**/
$app->get('/cookie', function(Request $request, Response $response, $args){
    $cookie = DefinitionUpdater::updateCookie();
    $response->getBody()->write( json_encode($cookie, JSON_UNESCAPED_SLASHES) );
    return $response->withHeader( 'Content-Type', 'application/json' );
})->setName('cookie');

});

$app->run();
$app->addErrorMiddleware(true, true, true);

?>

您键入提示 $group 作为 RouteCollectorProxy。编译器需要知道 class 的完全限定名,所以有两个选项:

  1. 在键入提示时使用 class 的完全限定名称(不推荐):

    $app->group('/api/v1', function( Slim\Routing\RouteCollectorProxy $group){});
    
  2. 添加另一个使用语句:

    use Slim\Routing\RouteCollectorProxy;
    

您的代码还有另一个问题。在路由组回调中,使用$group添加实际路由:

use Slim\Routing\RouteCollectorProxy;
$app->group('/api/v1', function(RouteCollectorProxy $group){
    $group->get('/list', function(Request $request, Response $response, $args){
        //
    });
});