bos570
bos570

Reputation: 1523

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. 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. 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.

Upvotes: 0

Views: 1965

Answers (1)

Mika Tuupola
Mika Tuupola

Reputation: 20387

You seem to have installed Slim 2. You are also mixing Slim 2 and Slim 3 syntax. To install Slim 3 issue the following command.

$ 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();

Upvotes: 4

Related Questions