Hi,
I’m struggling about passing session data to the view.
I’m using the Slim 4 Skeleton of @odan and use the SessionInterface configured to use Redis.
The user login is working, however what is the best practice to pass user_id, name and other informations from the session to the view? For the view I use the Responder object in the skeleton (don’t know why I use it, it was right here), and I have added on the “withTemplate” method a lot of addAttribute to add all the variables I need.
However it don’t seems the right way.
Example code:
/**
* Output rendered template.
*
* @param ResponseInterface $response The response
* @param string $template Template pathname relative to templates directory
* @param array $data Associative array of template variables
*
* @return ResponseInterface The response
*/
public function withTemplate(ResponseInterface $response, string $template, array $data = []): ResponseInterface
{
// Add some global attributes from session to view
$this->phpRenderer->addAttribute('user_id', $this->session->get('user_id'));
$this->phpRenderer->addAttribute('username', $this->session->get('username'));
$this->phpRenderer->addAttribute('tenant_id', $this->session->get('tenant_id'));
$this->phpRenderer->addAttribute('tenant_name', $this->session->get('tenant_name'));
$this->phpRenderer->addAttribute('flashes', $this->session->getFlash());
// Add global attributes from csrf to view
$nameKey = $this->csrf->getTokenNameKey();
$valueKey = $this->csrf->getTokenValueKey();
$name = $this->csrf->getTokenName();
$value = $this->csrf->getTokenValue();
$this->phpRenderer->addAttribute('csrf_nameKey', $nameKey);
$this->phpRenderer->addAttribute('csrf_name', $name);
$this->phpRenderer->addAttribute('csrf_valueKey', $valueKey);
$this->phpRenderer->addAttribute('csrf_value', $value);
return $this->phpRenderer->render($response, $template, $data);
}
I’ve also tried with a Middleware, but don’t matter if I place it on app, route, group, before, after any other, when I call addAttribute of PhpRenderer taking data from session, in the response are all empty fields.
Moreover, with the Flash messages is a mess, because I already have the messages shows up sometimes in two following request and sometimes never.
I’m really struggling trying to put all together to have a basic app and I hope I don’t need to take username from session on every single request and pass to the view (or should I?). The same for Flash messages… I need to put the code for taking them from session and add as data to the view
on every Action?