简体   繁体   English

在SLIM框架中使用中间件时出错

[英]Error Using Middleware in SLIM Framework

I have been at this for hours now and can not seem to figure out why it's not working. 我已经在这里呆了几个小时了,似乎无法弄清为什么它不起作用。 This my first time using SLIM and my first exposure to middleware. 这是我第一次使用SLIM,也是我第一次接触中间件。 I am trying to follow the tutorial listed on the slim website but just can't get to work. 我正在尝试按照苗条网站上列出的教程进行操作,但是无法正常工作。

My bootstrap code: 我的引导代码:

<?php

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

  $app = new Slim\Slim();


  $app->get('/test', function() {

    echo 'Hello, World'; 
 }); 

$mw = function ($request, $response, $next) {
    $response->getBody()->write('BEFORE');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER');

    return $response;
};


$app->add($mw); 
$app->run(); 

When I run just my slim url without the middleware it runs fine. 当我只运行我的苗条网址而没有中间件时,它运行良好。 I get Hello, World as the output when I runt http://mysite/test . 当我运行http:// mysite / testHello, World我得到Hello, World作为输出。 But when I add the middleware code as listed on the slim site I get the following error: 但是,当我添加苗条站点上列出的中间件代码时,出现以下错误:

Catchable fatal error: Argument 1 passed to Slim\Slim::add() must be an instance of Slim\Middleware, instance of Closure given, called in /Applications/XAMPP/xamppfiles/htdocs/project/api/public/index.php on line 22 and defined in /Applications/XAMPP/xamppfiles/htdocs/academy/api/vendor/slim/slim/Slim/Slim.php on line 1267

Am I missing something? 我想念什么吗? Does the middleware require some other setup? 中间件是否需要其他设置? The slim documentation is not very helpful when it comes to this. 苗条的文档在此方面不是很有帮助。 Any help appreciated. 任何帮助表示赞赏。

You seem to have installed Slim 2. You are also mixing Slim 2 and Slim 3 syntax. 您似乎已经安装了Slim2。您还在混合使用Slim 2和Slim 3语法。 To install Slim 3 issue the following command. 要安装Slim 3,请发出以下命令。

$ composer install slim/slim

Then use code like following: 然后使用如下代码:

<?php

require "vendor/autoload.php";

$app = new \Slim\App;

$mw = function ($request, $response, $next) {
    $response->getBody()->write("BEFORE");
    $response = $next($request, $response);
    $response->getBody()->write("AFTER");

    return $response;
};

$app->add($mw); 

$app->get("/test", function ($request, $response) {
    echo "Hello, World"; 
});

$app->run();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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