CodeIgniter Forums
Issue with Session - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11)
+--- Thread: Issue with Session (/showthread.php?tid=81776)



Issue with Session - Blasse133 - 04-27-2022

Hi everyone,

I'm new with CI (4.1.9) and my first steps went well.

But now I'm facing some issue with the session helper.

1.)
I added the following code in my BaseControllers InitController method.
PHP Code:
$this->session = \Config\Services::session(); 

When I use it with $this->session->get() in my controller everything works fine. But I get a
Code:
Call to a member function get() on null

as soon as I use it in one of my models.
How can I use the session service within my models?

2.) In case I check the existence of a session variable I get always a true, even if the variable is not existing.
PHP Code:
$this->session->has('test'); 
Now I'm checking, if this session is null.
Why is the return value of the code above always true?

Thanks in advance.

Could someone support me?


RE: Issue with Session - includebeer - 04-30-2022

There's no global object in CI4 like there was in CI3. So if you need to access the session in your model, you need to call the session service again. You can also use the session() helper to minimize the amount of code:
PHP Code:
$this->session session(); 

See https://codeigniter.com/user_guide/libraries/sessions.html#initializing-a-session for more details.

For your second question, I don't know why you always get true. All this function do is: 
PHP Code:
return isset($_SESSION[$key]); 
Source: https://github.com/codeigniter4/CodeIgniter4/blob/develop/system/Session/Session.php#L503


RE: Issue with Session - Blasse133 - 05-09-2022

(04-30-2022, 04:19 AM)THX includebeer Wrote: .
I will try your feedback and come back with a result.