如果我们看一下在 slim4网站和其他地方发布的中间件概念。
它应该在请求到达应用程序之前或向用户发送响应时执行。
问题是这样的,因为即使之前执行了一个中间件,应用程序也会调用一个容器:
给我看代码。
配置
'providers' => [,
App\ServiceProviders\Flash::class => 'http'
],
'middleware' => [
App\Middleware\Session::class => 'http,console',
],
会话中间件
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);
}
}
闪存消息容器
class Flash implements ProviderInterface
{
public static function register()
{
$flash = new Messages();
return app()->getContainer()->set(Messages::class, $flash);
}
}
执行应用
...
// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
AppFactory::setContainer($containerBuilder->build());
$app = AppFactory::create();
$providers = (array)$this->getConfig('providers');
array_walk($providers, function ($appName, $provider) {
if (strpos($appName, $this->appType) !== false) {
/** @var $provider ProviderInterface */
$provider::register();
}
});
$middlewares = array_reverse((array)$this->getConfig('middleware'));
array_walk($middlewares, function ($appType, $middleware) {
if (strpos($appType, $this->appType) !== false) {
$this->app->add(new $middleware);
}
});
....
$app->run();
结果
`Fatal error: Uncaught RuntimeException: Flash messages middleware failed. Session not found.`
Flash消息需要一个会话开始工作,我已经知道了,中间件应该负责这样做,但它总是在容器之后执行