Skip to content

Instantly share code, notes, and snippets.

@betweenbrain
Created February 27, 2016 16:34
Show Gist options
  • Save betweenbrain/d337caa01b2067f7b8aa to your computer and use it in GitHub Desktop.
Save betweenbrain/d337caa01b2067f7b8aa to your computer and use it in GitHub Desktop.
Slim 3 Middleware Execution Order Example (last in, first executed)
<?php

require 'vendor/autoload.php';

$app = new \Slim\App();

// Executed last as it's first in (FILE)
$app->add(function ($request, $response, $next) {
	// Execute the routes first
	$response = $next($request, $response);
	// Append the result from routes
	$response->getBody()->write(' Baz ');

	return $response;
});

$app->get('/', function ($req, $res, $args) {
	echo ' Bar ';
});

// Executed first as it's last in (LIFE)
$app->add(function ($request, $response, $next) {
	$response->getBody()->write(' Foo ');

	return $next($request, $response);
});

$app->run();
@DiyarD
Copy link

DiyarD commented Aug 13, 2016

Oh, I thought there was something wrong with my middlewares. it's executed in an ascending order.

@senshi-x
Copy link

Good example. It's not immediately obvious from the Slim docs on how the sequence of the middlewares is handled.

@wajdijurry
Copy link

Great explanation, thank you

@odahcam
Copy link

odahcam commented Nov 9, 2021

Thanks, was very useful explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment