简体   繁体   中英

Slim3 use reference is wrong

I'm tring to prepare a simple empty application with Slim3 and composer.

This is my front controller:

<?php

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


    $config=[];
    $config['displayErrorDetails'] = true;
    $config['addContentLengthHeader'] = false;
    $app = new \Slim\App(['settings' => $config]);

    foreach(glob("../app/dependencies/*.php") as $dependency){
        $dependency=include $dependency;
        $dependency($app);
    }
    foreach(glob("../app/middleware/*.php") as $middleware){
        $middleware=include $middleware;
        $middleware($app);
    }
    foreach(glob("../app/routes/*.php") as $route){
        $route=include $route;
        $route($app);
    }

    $app->run();

And this is the unique route file I have:

<?php 

return function (\Slim\App $app){
    $app->get('/', function (Request $request, Response $response) {
        $response->getBody()->write("Hello");
        return $response;
    });
};

When I run the application I got an error:

Argument 1 passed to Closure::{closure}() must be an instance of Request, instance of Slim\\Http\\Request given

I must add this "uses" to my route file:

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

Why php is taking the wrong (Slim) class for request and response? Really I have to prefix them for each controller file?

Really I have to prefix them for each controller file?

Yes. use declarations are per file as documented in the PHP manual :

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.


You might or might not be able to leave out the type in front of the parameter. Whether you are able to do so depends on whether Slim uses Reflection to determine whether to put the $request and $response object. Based off the error message you get I suppose you are able to simply remove the type.

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