Reputation: 9
this is the Session class in Session.php file
<?php
namespace app\core;
class Session
{
public function __construct()
{
session_start();
}
public function setFlash($key='', $message='')
{
$_SESSION['flash'][$key] = $message;
}
public function getFlash($key='')
{
return $_SESSION['flash'][$key] ?? false;
}
public function __destruct()
{
unset($_SESSION['flash']);
}
}
then i called session::setFlash() before redirecting the user to the home page after registering and call session::getFlash() in the view or the layout does not matter but i displayed nothing
here is the code
public function register(Request $request)
{
$registerModel = new RegisterModel;
if($request->isPost())
{
$registerModel->loadData($request->getBody());
if($registerModel->validate() && $registerModel->save())
{
Application::$app->session->setFlash('success', 'Thanks for registering');
$this->redirect('.');
}
return $this->render('register', [
'model' => $registerModel
]);
}
$this->setLayout('auth');
return $this->render('register', [
'model' => $registerModel
]);
}
this the view
<div class="container">
<?php if(Application::$app->session->getFlash('success')):?>
<div class="alert alert-success">
<?php echo Application::$app->session->getFlash('success'); ?>
</div>
<?php endif; ?>
{{content}}
</div>
i don`t know why it does not work
Upvotes: 1
Views: 256
Reputation: 5258
Two probable suspects:
'flash'
index when destructing the session. This means that when ONE request ends (the first one), the data is cleared. I'd recommend you rather remove a specific key from this array when calling getFlash()
, so that every message is only gotten once.session_write_close()
. This immediately ends the session and writes data to the session storage directly, making it available for the second request (the one that comes after the redirect). You have to call this before making the redirect.Side note: Your "custom MVC framework" code looks like it could live inside Laravel. If it does, the redirect()
method may already call the session_write_close()
so my second point would be moot.
Upvotes: 1