One of my colleagues moved to a different company and I got his source code of an existing project. I was shocked how messy the code looked. I am not a PHP developer so maybe this is a stupid question but it seems to me that he uses the $_SESSION too much and we get many errors regarding the Sessions. I was wondering if it would be good to encapsulate the $_SESSION and write for each value he uses an own method.
The problem I see with this code is that he uses the session object like this
$_SESSION['customer']['items'] = getItems() //returns an array
$_SESSION['article'][$Id]['name'] = utf8_decode[$received[1]];
So from my point of view I would store all his stuff in simple Popos and place those into the Session.
So the Popo for the customer would look like this
class CustomerPopo
{
private $_id;
private $_salutation;
private $_name;
private $_surename;
public function getId()
{
return $this->_id;
}
public function setId($value)
{
$this->_id = $value;
}
public function getSalutation()
{
return $this->_salutation;
}
public function setSalutation($value)
{
$this->_salutation = $value;
}
public function getName()
{
return $this->_name;
}
public function setName($value)
{
$this->_name = $value;
}
public function getSurename()
{
return $this->_surename;
}
public function setSurename($value)
{
$this->_surename = $value;
}
function CustomerPopo() {
}
}
And I imagined the SessionManager like this
class SessionManager
{
private static function getValue($valueName)
{
$value = SessionManager::getValueFromSession($valueName);
if (is_null($value)) {
//Handle stuff and do further checks
}
return $value;
}
private static function getValueFromSession($valueName)
{
$value = null;
if (isset($_SESSION[$valueName])) {
$value = $_SESSION[$valueName];
}
return $value;
}
private static function setValue($valueName, $value)
{
$_SESSION[$valueName] = $value;
}
private static function clearValue($valueName)
{
if (isset($_SESSION[$valueName])) {
unset($_SESSION[$valueName]);
}
}
public static function getCustomer()
{
$customer = '';
try {
$customer = SessionManager::getValue('customer');
} catch (Exception $e) {
$customer = '';
}
return $customer;
}
public static function setCustomer($customer)
{
SessionManager::setValue('customer', $customer);
}
}
With this I could kill some of the errors which arise from different spellings of the word customer/Customer/cusomter. I imagine the SessionManager would grow big because we have ~30 Session variables in the code.
Is there a design pattern which I could follow to implement such a SessionManager without making it worse in the end ? as stated I am not very familiar with PHP (yet).
EDIT:
Since the approach seems to be valid how can I handle the 30 Session variables i mentioned ? If I have a set/get and maybe a clear method for each value i will end up with 60-90 methods
Aucun commentaire:
Enregistrer un commentaire