Welcome Guest, Not a member yet? Register   Sign In
How to refer to 'session' in my code
#1

Hi Team,
Chugging my way through the 3->4 migration guide, I did as suggested and changed all my old $this->session calls to $session (and all the slightly different methods).
I then wondered how/where to initialise it as the superglobal is no more and v3 autoloading has been "improved".
Eventually I read about the BaseController and how to initialise stuff there.
However, the example in the forum (somewhere) suggests setting a private $session variable and then calling $this->session = \Config\Services:Confusedession(); in the constructor.
I think I now need to refer to the session object using $this->session.
So is is $session or $this->session?
I'm so bewildered.
cheers, Paul
Reply
#2

The upgrade guide was referring to the situation when in your controller, you call $this->load->library('session') in every method.

If you want to use the session in every controller, then you can load the session "globally" in the BaseController.

The code is already there, you only need to uncomment it. And yes, then you will refer to session via $this->session as you used to in CI3 (at least in controllers).

https://github.com/codeigniter4/CodeIgni...er.php#L56
Reply
#3

Code:
$session = \Config\Services::session();

$session on the left is just a handle , so if you have at the start of a class a property called "$sessionHandle" then the line would be

Code:
$this->sessionHandle = \Config\Services::session();

if its on the fly like using something thats not declared as a class property then :

Code:
$handle=  $session = \Config\Services::session();


now in a class of that handles login for CMS in each class method that wants to have access to session i do this at the start of every method

Code:
$session = \Config\Services::session();
//not using a class property my bad

and then from kicking off framework session you can use php S_SESSION eg

Code:
$session = \Config\Services::session();
$myarray = array( chr(rand(48,57)) , chr(rand(48,57)) , chr(rand(48,57)) , chr(rand(48,57)) , chr(rand(48,57)));
$_SESSION['captcha']= $myarray;
CMS CI4 A CMS system, runs out of the box written on top of CI4
Arch Book  CodeIgniter4 on Apache(pages 92-114) 
Reply
#4

Gents appreciate your replies.
My ci_3 app uses sessions a lot and the autoload just worked by magic everywhere.
Clearly the ci_v4 way to achieve something similar is to use the BaseController, in which case I now need to re-edit all my calls to use $this->session.
It might be worth reviewing the upgrade notes to make this a bit clearer, or perhaps I'm just a bit slow :-)
Thx Paul
Reply
#5

You can also use the Session Helper like this:

PHP Code:
// Get
$item session('item');

// Set
session()->set('item'$value); 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB