diff --git a/_config/requestprocessors.yml b/_config/requestprocessors.yml index 5c53964b1..8903a665d 100644 --- a/_config/requestprocessors.yml +++ b/_config/requestprocessors.yml @@ -3,6 +3,7 @@ Name: requestprocessors --- SilverStripe\Control\Director: middlewares: + SessionMiddleware: 'SilverStripe\Control\SessionMiddleware' RequestProcessor: 'SilverStripe\Control\RequestProcessor' FlushMiddleware: '%$SilverStripe\Control\FlushMiddleware' diff --git a/src/Control/Director.php b/src/Control/Director.php index 59fb66efd..1042f7e7e 100644 --- a/src/Control/Director.php +++ b/src/Control/Director.php @@ -132,13 +132,7 @@ class Director implements TemplateGlobalProvider } // Generate output - $result = static::handleRequest($request); - - // Save session data. Note that save() will start/resume the session if required. - $request->getSession()->save(); - - // Return - return $result; + return static::handleRequest($request); } /** diff --git a/src/Control/HTTPApplication.php b/src/Control/HTTPApplication.php index f3610f113..ed545a34c 100644 --- a/src/Control/HTTPApplication.php +++ b/src/Control/HTTPApplication.php @@ -96,8 +96,6 @@ class HTTPApplication implements Application // Ensure boot is invoked return $this->execute($request, function (HTTPRequest $request) { - // Start session and execute - $request->getSession()->init(); return Director::direct($request); }, $flush); } diff --git a/src/Control/SessionMiddleware.php b/src/Control/SessionMiddleware.php new file mode 100644 index 000000000..bae7f9644 --- /dev/null +++ b/src/Control/SessionMiddleware.php @@ -0,0 +1,28 @@ +getSession()->init(); + + // Generate output + $response = $delegate($request); + + // Save session data, even if there was an exception. + // Note that save() will start/resume the session if required. + } finally { + $request->getSession()->save(); + } + + return $response; + } +}