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?