I wanted to know the pros and cons of using session variables in class constructor or even within the methods of a class.
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 say by 8 types of users.
At the beginning of the process, when we are testing the login and password we will be able to recover the $userType
and save it inside the $_SESSION["userType"]=1
session, for example (ADMIN).
Later when I instantiate 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 value of the session 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 every time the object was instantiated. We would have more line of code, but we would not be using the session within the class.
What leads to a question: Is using a session within classes a good practice or not?
If yes , we could even save variables within the class (within methods) because we could access the direct value of $ _SESSION. And with that the code would have fewer rows. But I do not know if it would be good practice.
If not , we would have to start the class variables with the values of the session variables (each instantiation) and then use the variables within the class (as the theory says - good practice) , but would this create "unnecessary" lines? in the code.
What do you think?