简体   繁体   中英

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

I'm following the guide of slim 4 to create routes group but I get this error when I try to test the deployed heroku app:

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

what's wrong with my code?Maybe I've missed something?

<?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);

?>

You type hinted $group as RouteCollectorProxy . The compiler needs to know about the fully qualified name of the class, so there are two options:

  1. use fully qualified name of the class when type hinting (not recommended):

     $app->group('/api/v1', function( Slim\\Routing\\RouteCollectorProxy $group){});
  2. add another use statement:

     use Slim\\Routing\\RouteCollectorProxy;

There is also another problem with your code. In route group callback, you should use $group to add actual routes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM