im slighly confused, i was under the impression that when i use my baseController [code]…
- User
im slighly confused, i was under the impression that when i use my baseController
code - Assistant
im slighly confused, i was under the impression that when i use my baseController
class BaseController extends Controller
{
/**
* Session Session User Service & Session Cart Service
* @see app\components\SessionInterface.php
* @see app\components\SessionManager.php
* @see app\components\services\SessionUserService.php
* @see app\components\services\SessionCartService.php
*/
protected ?SessionUserService $_sessionUser = null;
protected ?SessionCartService $_sessionCart = null;
public function init()
{
/**
* Call to parent constructor
*
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*
* It is important to invoke the parent init method first to
* ensure that the properly set up before you add any additional
* functionality in this subclass.
*/
parent::init();
// ... initialization after configuration is applied...
/**
* Session Session User Service & Session Cart Service
* @see app\components\SessionInterface.php
* @see app\components\SessionManager.php
* @see app\components\services\SessionUserService.php
* @see app\components\services\SessionCartService.php
*/
$this->_sessionUser = ServiceLocator::get('sessionUserService');
$this->_sessionCart = ServiceLocator::get('sessionCartService');
if ($this->_sessionUser === null xor $this->_sessionCart === null)
{
throw new RuntimeException("Failed to load SessionUserService xor SessionCartService from ServiceLocator");
}
}
public function beforeAction($action): bool
{
if (!parent::beforeAction($action))
{
return false;
}
/**
* Layout Manager Breadcrumbs
* @see app\components\LayoutManager.php
* @var LayoutManager $layout
*
* Set generated breadcrumbs into LayoutManager
*/
$layout = \Yii::$app->layoutManager;
$breadcrumbs = [];
$layout->setBreadcrumbs($breadcrumbs);
/**
* Skip Session Validation for Routes
*
$route = \Yii::$app->requestedRoute;
// List of routes allowed without session validation
$allowedRoutes = [
'site/login',
'site/error',
'site/signup',
];
// Don't enforce session validation on public routes
if (in_array($route, $allowedRoutes, true))
{
return true;
}//*/
/**
* Middleware Enforce Session Security
*/
$sessionId = \Yii::$app->session->getId();
if ($this->_debugMode)
{
LogHelper::debug('Session ID: ' . $sessionId, ['session ID' => $sessionId]);
}
try
{
$sessionUser = $this->_sessionUser->findSessionUser($sessionId);
}
catch (Throwable $e)
{
if ($this->_debugMode)
{
LogHelper::debug('Error reading session data: ' . $e->getMessage(), [
'exception' => $e,
'route' => $route
]);
}
// Optionally handle error (for instance redirect or show maintenance)
return false;
}
if ($sessionUser !== null && $sessionUser->isExpired())
{
// Session invalid or expired - clean up session and related services
$this->_sessionUser->invalidate($sessionId);
$this->_sessionCart->clearCart();
// Destroy all session data will be removed
RoleHelper::userLogout(true);
\Yii::$app->session->setFlash(
'warning',
\Yii::t('app', 'Your session has expired or was invalidated. Please log in again.')
);
\Yii::$app->response->redirect(['site/login'])->send();
return false;
}
return true;
}
}
for all my controllers that need the same resources but i dont see a session for guest at all when im using pages.
Thanks for sharing your BaseController code. Based on your description, you expect your session services (SessionUserService and SessionCartService) to be initialized and used automatically in your controllers extending this BaseController, including for guest users (non-authenticated visitors). But you notice that for guest visits you don't see session information or you think the session isn't established or handled correctly.
Let's analyze the possible causes and clarify some points about session management in Yii2 (assuming you use Yii2 based on the code style and namespaces):
In Yii2, a session is not started automatically on every page request until you explicitly use the session or call $session->open() or $session->get(), or write something to it.
Your code references \Yii::$app->session->getId(). This will start the session if it’s not active already, but only if the code is executed.
Important: If there is no access to the session in some controller/action because the controller is not extending your BaseController or your beforeAction() isn't executed (e.g., in some pages or error handlers), the session would not be started and thus no session ID will be sent or stored.
Your beforeAction() checks the current route and skips session validation for some public routes like site/login, site/error, and site/signup. For all other routes, it tries to find the session user and check expiration.
If the visitor is a guest (non-authenticated), findSessionUser($sessionId) may return null (no logged user), meaning your sessionUserService might treat guests differently or ignore them.
Your code depends on $this->_sessionUser = ServiceLocator::get('sessionUserService'); and $this->_sessionCart = ServiceLocator::get('sessionCartService');.
You should verify:
Your sessionUserService and sessionCartService are well defined and handle guest sessions too.
Whether they create, load, or initialize any session data for guest users.
If some controllers do not extend BaseController, or their beforeAction() does not call parent::beforeAction(), then your session initialization and validation code will not run.
Sometimes, sessions are started but cookies are not sent or saved by the browser due to:
Secure cookie flag on HTTP (no HTTPS)
Domain/path mismatch
HTTP headers conflicts (e.g., caching, redirects)
Check your browser devtools for cookie presence and session id.
In your BaseController::init() or very early in your application, try explicitly opening the session:
\Yii::$app->session->open();
This will ensure that the session is started and cookie is sent to the browser even for guests.
Add logging in your controller's beforeAction or init:
$session = \Yii::$app->session;
if (!$session->isActive) {
$session->open();
}
LogHelper::debug('Session ID: ' . $session->getId() . ', Active? ' . ($session->isActive ? 'yes' : 'no'));
Check if the session is active or not for guest requests.
Does findSessionUser($sessionId) return null for guest users? If yes, your services may not create guest session data by design.
Make sure your session cart and session user services handle guest sessions or fallback to anonymous user sessions.
Your BaseController initializes session-related services only when the controller and its beforeAction() method run.
Page requests routed to controllers NOT inheriting BaseController or beforeAction() skipping parent calls won't initialize sessions.
Yii by default only starts sessions lazily — accessing the session starts it.
Guest users may not have a "session user" record, only a PHP session cookie.
If you want to support sessions for guests, ensure you explicitly open the session and your session services accommodate guest users.
If you want, I can help you adjust your code to explicitly open sessions or make it better handle guest users. Let me know!
Not yet included in a published release.