Skip to content

Commit

Permalink
[+]: add a interface && a wrapper class for the database-connection
Browse files Browse the repository at this point in the history
  • Loading branch information
voku committed Oct 15, 2017
1 parent 88d9011 commit ab93c31
Show file tree
Hide file tree
Showing 5 changed files with 191 additions and 28 deletions.
28 changes: 22 additions & 6 deletions README.md
Expand Up @@ -41,7 +41,7 @@ The code is heavily commented and generates no warnings/errors/notices when PHP'

## Requirements

PHP 5+ with the **mysqli extension** activated, MySQL 4.1.22+
PHP 5.x or 7.x with the **mysqli extension** activated, MySQL 4.1.22+

## How to install

Expand All @@ -58,17 +58,33 @@ After installing, you will need to initialise the database table from the *insta
```php
<?php
use voku\db\DB;
use voku\helper\DbWrapper4Session;
use voku\helper\Session2DB;

// include autoloader
require_once 'composer/autoload.php';

$db = DB::getInstance('yourDbHost', 'yourDbUser', 'yourDbPassword', 'yourDbName');

// example
// $db = DB::getInstance('localhost', 'root', '', 'test');
$db = DB::getInstance(
'hostname', // e.g. localhost
'username', // e.g. user_1
'password', // e.g. ******
'database', // e.g. db_1
'port', // e.g. 3306
'charset', // e.g. utf8mb4
true, // e.g. true|false (exit_on_error)
true, // e.g. true|false (echo_on_error)
'', // e.g. 'framework\Logger' (logger_class_name)
'', // e.g. 'DEBUG' (logger_level)
array(
'session_to_db' => true,
)
);

// you can also use you own mysqli implementation via the "Db4Session"-interface,
// take a look at the "DbWrapper4Session"-class for a example
$dbWrapper = new DbWrapper4Session($db);

$session = new Session2DB();
$session = new Session2DB($dbWrapper);

// from now on, use sessions as you would normally
// this is why it is called a "drop-in replacement" :)
Expand Down
51 changes: 51 additions & 0 deletions src/voku/helper/Db4Session.php
@@ -0,0 +1,51 @@
<?php

namespace voku\helper;

interface Db4Session
{

/**
* @return bool
*/
public function close();

/**
* @param mixed $var
*
* @return mixed
*/
public function escape($var);

/**
* @param string $sql
* @param string $string
*
* @return array|string <p>empty string on error</p>
*/
public function fetchColumn($sql, $string);

/**
* @return bool
*/
public function ping();

/**
* @param string $sql
*
* @return mixed|false <p>false on error</p>
*/
public function query($sql);

/**
* @param string $string
*
* @return string
*/
public function quote_string($string);

/**
* @return bool
*/
public function reconnect();
}
102 changes: 102 additions & 0 deletions src/voku/helper/DbWrapper4Session.php
@@ -0,0 +1,102 @@
<?php

namespace voku\helper;

use voku\db\DB;

class DbWrapper4Session implements Db4Session
{

/**
* @var DB
*/
private $db;

/**
* SimpleMySQLiWrapper constructor.
*
* @param null|DB $db
*/
public function __construct($db = null)
{
if (null !== $db) {
$this->db = $db;
} else {
$this->db = DB::getInstance();
}
}

/**
* @inheritdoc
*/
public function close()
{
return $this->db->close();
}

/**
* @inheritdoc
*/
public function escape($var)
{
return $this->db->escape($var);
}

/**
* @inheritdoc
*/
public function fetchColumn($sql, $string)
{
$result = $this->db->query($sql);

return $result->fetchColumn($string);
}

/**
* @inheritdoc
*/
public function ping()
{
return $this->db->ping();
}

/**
* @inheritdoc
*/
public function query($sql)
{
return $this->db->query($sql);
}

/**
* @inheritdoc
*/
public function quote_string($string)
{
return $this->db->quote_string($string);
}

/**
* @inheritdoc
*/
public function reconnect()
{
return $this->db->reconnect();
}

/**
* @return DB
*/
public function getDb()
{
return $this->db;
}

/**
* @return DbWrapper4Session
*/
public static function getInstance()
{
return new self();
}
}
30 changes: 10 additions & 20 deletions src/voku/helper/Session2DB.php
Expand Up @@ -2,9 +2,6 @@

namespace voku\helper;

use voku\db\DB;
use voku\db\Result;

/**
* A PHP library acting as a drop-in replacement for PHP's default session handler, but instead of storing session
* data in flat files it stores them in a database, providing both better performance and better security and
Expand Down Expand Up @@ -48,7 +45,7 @@ class Session2DB implements \SessionHandlerInterface
const flashDataVarName = '_menadwork_session_flashdata_ec3asbuiad';

/**
* @var DB
* @var Db4Session
*/
private $db;

Expand Down Expand Up @@ -280,14 +277,14 @@ class Session2DB implements \SessionHandlerInterface
*
* Default is <i>60</i>
*
* @param DB|null $db [Optional] A database instance from voku\db\DB ("voku/simple-mysqli")
* @param Db4Session|null $db [Optional] A database instance from voku\db\DB ("voku/simple-mysqli")
*/
public function __construct($security_code = '', $session_lifetime = '', $lock_to_user_agent = false, $lock_to_ip = false, $gc_probability = 1, $gc_divisor = 1000, $table_name = 'session_data', $lock_timeout = 60, DB $db = null)
public function __construct($security_code = '', $session_lifetime = '', $lock_to_user_agent = false, $lock_to_ip = false, $gc_probability = 1, $gc_divisor = 1000, $table_name = 'session_data', $lock_timeout = 60, Db4Session $db = null)
{
if (null !== $db) {
$this->db = $db;
} else {
$this->db = DB::getInstance();
$this->db = DbWrapper4Session::getInstance();
}

// If no DB connections could be found, then
Expand Down Expand Up @@ -540,10 +537,7 @@ public function get_active_sessions()
';

// counts the rows from the database
$result = $this->db->query($query);

// return the number of found rows
return $result->fetchColumn('count');
return (int)$this->db->fetchColumn($query, 'count');
}

/**
Expand Down Expand Up @@ -815,16 +809,12 @@ public function read($session_id)
LIMIT 1
";

$result = $this->db->query($query);
$data = $this->db->fetchColumn($query, 'session_data');

// if anything was found
if (is_object($result) && $result->num_rows > 0) {

// return found data
$fields = $result->fetchArray();

if ($data) {
// don't bother with the unserialization - PHP handles this automatically
return $fields['session_data'];
return $data;
}

// on error return an empty string - this HAS to be an empty string
Expand Down Expand Up @@ -858,7 +848,7 @@ private function _release_lock($session_id)
$result_lock = $this->db->query($query);

// if there was an error, then stop the execution
if (!$result_lock instanceof Result || $result_lock->num_rows !== 1) {
if (!$result_lock) {
return false;
}

Expand All @@ -880,7 +870,7 @@ private function _get_lock($session_id)
$result_lock = $this->db->query($query_lock);

// if there was an error, then stop the execution
if (!$result_lock instanceof Result || $result_lock->num_rows !== 1) {
if (!$result_lock) {
return false;
}

Expand Down
8 changes: 6 additions & 2 deletions tests/SimpleSessionTest.php
Expand Up @@ -2,6 +2,7 @@

use voku\db\DB;
use voku\helper\Bootup;
use voku\helper\DbWrapper4Session;
use voku\helper\Session2DB;

# running from the cli doesn't set $_SESSION
Expand Down Expand Up @@ -35,7 +36,10 @@ class SimpleSessionTest extends PHPUnit_Framework_TestCase
*/
public function __construct()
{
$this->db = DB::getInstance('localhost', 'root', '', 'mysql_test');
parent::__construct();

$db = DB::getInstance('localhost', 'root', '', 'mysql_test');
$this->db = new DbWrapper4Session($db);
}

public function testGetSettings()
Expand Down Expand Up @@ -91,7 +95,7 @@ public function testBasic3WithDbCheck()

self::assertSame(123, $_SESSION['test']);

$result = $this->db->select('session_data', array('hash' => $this->session2DB->get_fingerprint()));
$result = $this->db->getDb()->select('session_data', array('hash' => $this->session2DB->get_fingerprint()));
$data = $result->fetchArray();
$sessionDataFromDb = unserialize($data['session_data']);
self::assertSame(123, $sessionDataFromDb['test']);
Expand Down

0 comments on commit ab93c31

Please sign in to comment.