Last active
November 20, 2015 17:47
-
-
Save michaelachrisco/b225b2f4976a0ad100a6 to your computer and use it in GitHub Desktop.
DB Adapter pattern for Laravel 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* In the Adapter Design Pattern, a class converts the interface of one class | |
* to be what another class expects. | |
* In this case, we use Adapters as interfaces to custom made queries. | |
*/ | |
namespace App\Adapters; | |
use DB; | |
class Adapter{ | |
public $dbConnection; | |
public $isCached;// true/false flag | |
public $cachedArray; // if object is cached, then store in the cached Array | |
public $DebugFlag; | |
public function __construct($cache = false, $debug = false){ | |
if (getenv('APP_ENV') != 'production'){ | |
$db = DB::connection('test'); | |
} | |
else { | |
$db = DB::connection('production'); | |
} | |
$this->dbConnection = $db; | |
$this->isCached = $cache; | |
$this->DebugFlag = $debug; | |
} | |
public function addToCache($SQL, $result){ | |
if ($this->isCached == true){ | |
// $minutes = 10; | |
// return Cache::add($SQL, $result, $minutes); | |
$this->cachedArray[$SQL] = $result; | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
public function findFromCache($SQL){ | |
if (!empty($this->cachedArray) && array_key_exists($SQL, $this->cachedArray)){ | |
return $this->cachedArray[$SQL]; | |
} | |
else { | |
return ''; | |
} | |
} | |
public function findOrAddToCache($SQL){ | |
//if the Object is Cached and the key exists | |
if ($this->isCached && !empty($this->findFromCache($SQL))){ | |
$result = $this->findFromCache($SQL); | |
} | |
//if the Object is Cached and the key does not exist | |
elseif($this->isCached && empty($this->findFromCache($SQL))){ | |
$result = $this->dbConnection->select($SQL); | |
$this->addToCache($SQL, $result); | |
} | |
//if the Object is not Cached | |
else{ | |
$result = $this->dbConnection->select($SQL); | |
} | |
return $result; | |
} | |
public function toList($sqlString){ | |
if ($this->isCached){ | |
return (array)$this->findOrAddToCache($sqlString); | |
} | |
$raw_collection = $this->dbConnection->select($sqlString); | |
return (array)$raw_collection; | |
} | |
public function toOne($raw){ | |
if ($this->isCached == true){ | |
$raw_collection = $this->findOrAddToCache($raw); | |
} | |
else{ | |
$raw_collection = $this->dbConnection->select($raw); | |
} | |
if (empty($raw_collection)){ | |
return []; | |
} | |
else { | |
return $raw_collection[0]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To note, this adapter should only be used when its faster to create the SQL yourself rather than using Laravel 5 ORM. This is mainly used for older DB's and SQL development.