I would guess that the session is not startet when you try to fetch data from an upper layer. I would try to implement it more “MVC friendly” and pass the data from the controller to the template engine instead.
The Twig addGlobal works only as long as no other Twig template has been rendered, because after the first rendering twig blocks all changes to the global variables
I would refactor the getUserDetails method a little pit and pass the UserId from the session instead of fetching within the Model layer via the session. Otherwise it breaks MVC.
Example:
public function getUserDetails(int $userId): Users
{
return Users::select(
[
"id",
"username",
"first_name",
"middle_name",
"last_name",
"email"
]
)->find($userId);
}
Middleware:
<?php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Exception\HttpUnauthorizedException;
// ...
class UserAuthenticationMiddleware implements MiddlewareInterface
{
// ...
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
/* @var Twig $view */
$view = $this->container->get('view');
/* @var Helper $session */
$session = $this->container->get('session');
$userId = $session->get('userID');
if (!$userId) {
throw new HttpUnauthorizedException();
}
$environment = $view->getEnvironment();
$environment->addGlobal(
'authUser',
[
'userDetails' => $this->container->get('auth')->getUserDetails($userId)
]
);
$environment->addGlobal('authUserPermissions', $session->get('userPermissions'));
$environment->addGlobal('authorized', true);
return $handler->handle($request);
}
}
My example Middleware should solve the (lazy loading) Session issue. I would try this first. If it works, then everything should be fine.
If you get a Twig error message like Unable to add global "variablename" as the runtime or the extensions have already been initialized. then you may try this workaround: Twig dynamic global variables.
@pauhoms thanks for you input. Ill see about the conversion to array. Currently the model works well for me. I have been experience issue with using “with” option on the model not sure what I did but its working now in one of my api calls.