Skip to content

Instantly share code, notes, and snippets.

@michaelachrisco
Last active November 20, 2015 17:47
Show Gist options
  • Save michaelachrisco/b225b2f4976a0ad100a6 to your computer and use it in GitHub Desktop.
Save michaelachrisco/b225b2f4976a0ad100a6 to your computer and use it in GitHub Desktop.
DB Adapter pattern for Laravel 5
<?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];
}
}
}
@michaelachrisco
Copy link
Author

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.

<?php
/* +FooAdapter+ Interface between Laravel and Database.dbo.Foo
*/
namespace App\Adapters;
use DB;

class FooAdapter extends Adapter{

  public function all() {
    $depSQL="SELECT *
             FROM Database.dbo.Foo" ;
   return $this->toList($depSQL);
  }
}

//Within your Controller or Service Object:
$fooAdapter = new FooAdapter;
$result = $fooAdapter->all();
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment