If we look at the Middleware concept published on the slim4 website, we can see that Middleware is one before application, and we can include Middleware or after it.
The question is this, because even if a Middleware is executed before, a container is called before by the application:
Show me the code.
Session Middleware
class Session
{
public function __invoke(Request $request, RequestHandler $handler)
{
if (session_status() !== PHP_SESSION_ACTIVE) {
$settings = app()->getConfig('settings.session');
if (!is_dir($settings['filesPath'])) {
mkdir($settings['filesPath'], 0777, true);
}
$current = session_get_cookie_params();
$lifetime = (int)($settings['lifetime'] ?: $current['lifetime']);
$path = $settings['path'] ?: $current['path'];
$domain = $settings['domain'] ?: $current['domain'];
$secure = (bool)$settings['secure'];
$httponly = (bool)$settings['httponly'];
session_save_path($settings['filesPath']);
session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
session_name($settings['name']);
session_cache_limiter($settings['cache_limiter']);
session_start();
}
return $handler->handle($request);
}
}
Flash Message Container
class Flash implements ProviderInterface
{
public static function register()
{
$flash = new Messages();
return app()->getContainer()->set(Messages::class, $flash);
}
}
**Registers **
/**
* register Middleware
*
* @return void
*/
public function registerMiddleware()
{
$middlewares = array_reverse((array)$this->getConfig('middleware'));
array_walk($middlewares, function ($appType, $middleware) {
if (strpos($appType, $this->appType) !== false) {
$this->app->add(new $middleware);
}
});
}
/**
* register providers
*
* @return void
*/
public function registerProviders()
{
$providers = (array)$this->getConfig('providers');
array_walk($providers, function ($appName, $provider) {
if (strpos($appName, $this->appType) !== false) {
/** @var $provider ProviderInterface */
$provider::register();
}
});
}
**Result **
Fatal error: Uncaught RuntimeException: Flash messages middleware failed. Session not found.
Flahs message needs a session started to work this already I know, and Middleware should be responsible for doing this, but it is always executed after the container