Session variables $_SESSION vs class variables in PHP

Asked

Viewed 872 times

0

I wanted to know the pros and/or cons of using session variables on class constructor or even within class methods.

Let’s say I have the following class:

class minhaClasse {
    private $arrEnvSettings;

    public function __construct(array $setParam=NULL) {

        $arrIni["userType"] = $_SESSION["userType"];
        //$arrIni["outrasVar"] = "valor padrão de inicialização";


        //Unindo $setParam com $arrIni
        //Permite mudar os valores de inicialização
        if(!is_null($setParam)){
            $this->$arrEnvSettings =  array_merge($arrIni,$setParam);
        }
        else{
            $this->$arrEnvSettings =$arrIni;
        }
    }

    public function homePage() {

        if($this->$arrEnvSettings["userType"]=1){
            //Mostrar home page admin
        }
        else{
            //Mostrar home page para não admin
        }

    }
}

As an example I have a system that was designed to be accessed by say 8 types of users. Right at the beginning of the process, when we are testing the login and password we can recover the $userType and record within the session $_SESSION["userType"]=1 for example (ADMIN).

Later when I am instantiating the object, I could use the following two examples:

//Exemplo - 1
$objSite = new minhaClasse();
echo $objSite->homePage();

//ou

//Exemplo - 2
$arrInicializ ["userType"]= $_SESSION["userType"];
$objSite = new minhaClasse(arrInicializ);
echo $objSite->homePage();

In example 1 it would not be necessary to initialize the variable with the session value because it is already done in the constructor (default). This would save many lines of code every time the object was used.

In the second example we would have to initialize the variable each time the object was instantiated. We would have more line of code, but we wouldn’t be using the session inside the class.

What leads to a question: using session within classes is good practice or not?

If yes, we could even save variables within the class (within the methods) because we could access the direct value of $_SESSION. And with that the code would be with fewer lines. But I don’t know if it would be a good practice.

If not, we would have to start the class variables with the values of the session variables (at each instantiation) and then use the variables within the class (as the theory says - good practice), but that would create "unnecessary lines?" in the code.

What do you think?

1 answer

1

In that case, I share the same idea I learned when I started learning Python: Explicit is better than implicit

Why?

When I step from the data I am going to work with inside a class, it is easier to know what will be used. When implicitly you use the $_SESSION within the class, you may be limiting its use to several factors.

I mean the following: If you need to make any changes to the data used, you would have to "sift through" the source code of your class. And I don’t think it’s cool, because maybe you have to change all the points where you’re instantiating this class.

As I said, I prefer "explicit rather than "implicit". So I would do it this way:

class MinhaClasse
{
         protected $dadosSessao = [];

         public function __construct(array $dadosSessao, $outro = null)
         {
               $this->setDadosSessao($dadosSessao);
         }

         public function setDadosSessao($dadosSessao)
         {
             $this->dadosSessao = $dadosSessao;
         }


}

The way to use it would be:

 $minha_classe = new MinhaClasse($_SESSION, OUTRO_VALOR);

An interesting option that you can do in this case is to create a static method, which will serve to create the instance of your class based on $_SESSION. This method will work as a factory.

class Session {

     // Pode receber os dados indepedente do mecanismo do PHP ou não

     public function __construct(array $data)

     {
          $this->data = $data;
     }

     public static function createFromGlobalSession()
     {
          return new static($_SESSION);
     }
}

$session = Session::createFromGlobalSession();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.