I am implementing my first app using MVC.
I would like to know if the approach I thought for the session system is a good and scalable one.
Well, basically a session is stored in my MySQL database and it is represented as a Session Model object.
I also created a SessionDataMapper
that makes the connection between the model layer and the database layer (is what I just said right?) for the Session
object.
class Session extends Model{
private $id;
private $timeCreated;
private $timeUpdated;
private $userId;
private $ip;
public function __construct($sessionData){
... some initialization (hidden for better reading)
}
... some getter methods (hidden for better code reading)
}
_
class SessionDataMapper extends DataMapper{
private $connection;
private static $sessionTimeout = 2*60*60; //2 hours
public function __construct(){
$this->connection = (new \Utils\DatabaseConnection())->getConnection();
}
/*
* @returns \Models\Session or null
*/
public function create($sessionId){
//On date retrieve deletes the expired sessions
$query = $this->connection->prepare("BEGIN TRANSACTION;
DELETE FROM sessions WHERE time_updated <= :expirationTime;
SELECT * FROM sessions WHERE session_id = :sessionId;
COMMIT;");
$query->bindParam(":expirationTime", time() - self::$sessionTimeout, PDO::PARAM_STR);
$query->bindParam(":sessionId", $sessionId, PDO::PARAM_STR);
if($query->execute()){
$sessionData = $query->fetch(PDO::FETCH_OBJ);
if($sessionData != false){
return new Session(array(
"sessionId" => $sessionData->session_id,
"timeCreated" => $sessionData->time_created,
"timeUpdated" => $sessionData->time_updated,
"userId" => $sessionData->user_id,
"ip" => $sessionData->ip
));
}else{
return null;
}
}else{
return null;
}
}
/*
* @returns boolean
*/
public function save(Session $session){
}
/*
* @returns boolean
*/
public function insert(Session $session){
$query = $this->connection->prepare("INSERT INTO sessions (session_id, time_created, time_updated, user_id, ip) VALUES
(:sessionId, :timeCreated, :timeUpdated, :userId, :ip);");
$query->bindParam(":sessionId", $session->getId(), PDO::PARAM_STR);
$query->bindParam(":timeCreated", $session->getTimeCreated(), PDO::PARAM_STR);
$query->bindParam(":timeUpdated", $session->getTimeUpdated(), PDO::PARAM_STR);
$query->bindParam(":userId", $session->getUserId(), PDO::PARAM_STR);
$query->bindParam(":ip", $session->getIp(), PDO::PARAM_STR);
return $query->execute();
}
/*
* @returns void
*/
public function delete(Session $session){
}
}
I would like to focus on my SessionDataMapper::create()
method. As you can see I added a bit logic to make it remove the expired sessions when a session is retrieved. Is this a good approach? If not what would you recommend?
Also if you have any comments to the rest of the code, they are appreciated.
Thanks!