CodeIgniter Forums
How to start session globally? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to start session globally? (/showthread.php?tid=71769)

Pages: 1 2 3


RE: How to start session globally? - kilishan - 09-21-2018

Personally, I'd put it in a library of some sort. Whatever models you're pulling results from will already have the db connection, and the library would just compile the stats from the different models.


RE: How to start session globally? - macruzgi - 11-04-2019

(09-21-2018, 06:16 AM)kilishan Wrote: My suggestion: don't worry about loading the session globally. First - that means that if the session isn't needed it isn't loaded which can be good for performance and some security things, IIRC. Second - whenever you first call the service, or use the the service() helper method, the session will be automatically initialized and ready for use.

Code:
// These all ensure session is initialized:
$session = \Config\Services::Session();
session('key');
session()->get('key');
session()->set('key', $value);



211/5000
In CI3 the session was held globally.
I have started the session in BaseController and assigned the values to the respective one from one controller, but when evaluating it in another controller the values do not exist.

PHP Code:
//BaseController
$this->sesion  = \Config\Services::session(); 

Controller where I assign the values to the logged in user session:

PHP Code:
$datosEnSesion = array(
 
'usuario'=>$usuarioEncontrado->usuario,
 
'usuario_nombre'=>$usuarioEncontrado->usuario_nombre,
 
'usuario_estado'=>$usuarioEncontrado->usuario_estado,
 
'chequear'=>true,
 
'MenuUsuarioLogueado'=>$MenuUsuarioLogueado,
 
'ids_modulo_opciones'=>$ids_modulo_opciones
 
);
 
//agrego los datos a una sesion
$this->sesion->set($datosEnSesion); 


If I print those values on the current controller, it works correctly, but when evaluating them on another controller, it no longer exists.
Other controller:

PHP Code:
public function __construct(){
 
//parent::__construct();
 //establezco la zona horario par El Salvador
 
date_default_timezone_set('America/El_Salvador');
 
//comprobamos si el usuario está logueado
 
 
$this->sesion session();
 if(
$this->sesion->chequear != true)
 {
 
//si no estoy logueado que me envie a index
 
return redirect()->to(base_url());
 }
 
 
 } 

Any idea why that happens?


RE: How to start session globally? - macruzgi - 11-04-2019

(09-21-2018, 06:16 AM)kilishan Wrote: My suggestion: don't worry about loading the session globally. First - that means that if the session isn't needed it isn't loaded which can be good for performance and some security things, IIRC. Second - whenever you first call the service, or use the the service() helper method, the session will be automatically initialized and ready for use.

Code:
// These all ensure session is initialized:
$session = \Config\Services::Session();
session('key');
session()->get('key');
session()->set('key', $value);

In CI3 the session was held globally.
I have started the session in BaseController and assigned the values to the respective one from one controller, but when evaluating it in another controller the values do not exist.

BaseController:

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

Controller where I assign the values to the logged in user session:

PHP Code:
//agrego los datos del asuario al array 
$datosEnSesion = array(
 
'usuario'=>$usuarioEncontrado->usuario,
 
'usuario_nombre'=>$usuarioEncontrado->usuario_nombre,
 
'usuario_estado'=>$usuarioEncontrado->usuario_estado,
 
'chequear'=>true,
 
'MenuUsuarioLogueado'=>$MenuUsuarioLogueado,
 
'ids_modulo_opciones'=>$ids_modulo_opciones
 
);
 
//agrego los datos a una sesion
$this->sesion->set($datosEnSesion); 

If I print those values on the current controller, it works correctly, but when evaluating them on another controller, it no longer exists.
Other controller:

PHP Code:
public function __construct(){
 
//parent::__construct();
 //establezco la zona horario par El Salvador
 
date_default_timezone_set('America/El_Salvador');
 
//comprobamos si el usuario está logueado

 
$this->sesion session();
 if(
$this->sesion->chequear != true)
 {
 
//si no estoy logueado que me envie a index
 
return redirect()->to(base_url());
 }
 
 
//cargo los modelos anecestiar
 
 


Any idea why that happens?


RE: How to start session globally? - macruzgi - 11-04-2019

(09-21-2018, 04:35 AM)happyape Wrote: I looked at the documentation, https://bcit-ci.github.io/CodeIgniter4/libraries/sessions.html?#initializing-a-session, which says,

Code:
To access and initialize the session:

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

Am I supposed to put this code in the constructor of every Controller class where I need to manipulate session data?

I found that I can also use start session using this helper
Code:
session()->start();
but again I need to declare that in all files before I can use session.

I need to know the same for db and custom common functions helper file.

$db = \Config\Database::connect();

All I am trying to find out if I should be placing these in a common file? Or perhaps, declaring in each file is the suggested practice???

Regards.
With the DB connection you better use functions in your controllers and models.
The helpers use them for external libraries of a third party that do not need connection to the DB.


RE: How to start session globally? - dave friend - 11-04-2019

(11-04-2019, 10:48 AM)macruzgi Wrote: If I print those values on the current controller, it works correctly, but when evaluating them on another controller, it no longer exists.
Other controller:

PHP Code:
public function __construct(){
 
//parent::__construct();
 //establezco la zona horario par El Salvador
 
date_default_timezone_set('America/El_Salvador');
 
//comprobamos si el usuario está logueado
 
 
$this->sesion session();
 if(
$this->sesion->chequear != true)
 {
 
//si no estoy logueado que me envie a index
 
return redirect()->to(base_url());
 }
 
 
 } 

Any idea why that happens?

Does the above class extend BaseController? You MUST uncomment the line

PHP Code:
//parent::__construct(); 

Because if that does not run then the BaseController does not get to run this line

PHP Code:
//BaseController
$this->sesion  = \Config\Services::session(); 


In the example above you also do this

PHP Code:
$this->sesion session(); 

Don't do that!

$this->sesion should be set up by BaseController and so is ready for use.


RE: How to start session globally? - macruzgi - 11-04-2019

It is correct that class extends from BaseController, I have commented the line parent ::__ construct () because if it does not throw me the error of: Cannot call constructor



PHP Code:
namespace App\Controllers;
use 
App\Models\Modeloejemplo;
class 
Demo extends BaseController
{
public function 
__construct(){
 
//parent::__construct();
 //establezco la zona horario par El Salvador
 
date_default_timezone_set('America/El_Salvador');
 
//comprobamos si el usuario está logueado
 
$this->sesion session();
 if(
$this->sesion->chequear != true)
 {
 
//si no estoy logueado que me envie a index
 
return redirect()->to(base_url());
 }
 
 
 }


Also, if I do not declare
PHP Code:
$this->session session(); 
the error throws me making a point that the session property is not defined


RE: How to start session globally? - dave friend - 11-04-2019

PHP Code:
namespace App\Controllers;
use 
App\Models\Modeloejemplo;
class 
Demo extends BaseController
{
public function 
__construct(){
    parent::__construct();  // <<< YOU MUST CALL THIS!! 

If calling that causes an error you must figure out why and fix it.


RE: How to start session globally? - macruzgi - 11-05-2019

(11-04-2019, 09:14 PM)dave friend Wrote:
PHP Code:
namespace App\Controllers;
use 
App\Models\Modeloejemplo;
class 
Demo extends BaseController
{
public function 
__construct(){
    parent::__construct();  // <<< YOU MUST CALL THIS!! 

If calling that causes an error you must figure out why and fix it.


Regards.
That is not possible, the BaseController class does not have its own constructor, so there is no explicit constructor that can be invoked.


RE: How to start session globally? - dave friend - 11-05-2019

(11-05-2019, 07:51 AM)macruzgi Wrote: That is not possible, the BaseController class does not have its own constructor, so there is no explicit constructor that can be invoked.

Oh... Right. Blush
Never mind.


RE: How to start session globally? - InsiteFX - 11-05-2019

This is how I set up sessions on my BaseController.

PHP Code:
<?php
namespace App\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use CodeIgniter\Controller;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Config\Services;
use 
Psr\Log\LoggerInterface;

/**
 * Class BaseController
 *
 * @package App\Controllers
 */
class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [
        'auth',
        'utility',
    ];

    /**
     * @var string - Holds the session instance
     */
    protected $session;

    /**
     * Constructor.
     *
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     * @param LoggerInterface            $logger
     */
    
public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        
// Do Not Edit This Line
        
parent::initController($request$response$logger);

        
//--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.:
        // $this->session = \Config\Services::session();

        // Ensure that the session is started and running
        if (session_status() == PHP_SESSION_NONE)
        {
            $this->session Services::session();
        }
    }

}
   // End of Class BaseController.

/**
 * -----------------------------------------------------------------------
 * Filename: BaseController.php
 * Location: ./app/Controllers/BaseController.php
 * -----------------------------------------------------------------------
 */ 

See if that will work for you.

Just call it like this:

PHP Code:
$this->session