Skip to content

Instantly share code, notes, and snippets.

@tommyready
Last active June 7, 2020 21:57
Show Gist options
  • Save tommyready/2803f4d7ae7522f707bd090c03bd1c6b to your computer and use it in GitHub Desktop.
Save tommyready/2803f4d7ae7522f707bd090c03bd1c6b to your computer and use it in GitHub Desktop.
Laravel 5 Service that Wraps PDO to call StoredProcedure with Multiple ResultSets and Return Arrays of Data
<?php
namespace App\Services;
class PDOService {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
/**
@param $storedProcedureName string - Name of Stored Procedure that needs to be called
@param $parameters array - Array of Values for Stored Procedure (They need to be in the correct order)
@return Array of Resultsets
Example:
Use App\Services\PDOService;
$pdoService = new PDOService('myconnection');
$spParameters = [12345,'string'];
$spName = 'sp_MyStoredProcedure';
$spData = $pdoService->callStoredProcedure($spName,$spParameters);
*/
public function callStoredProcedure($storedProcedureName,$parameters = array()) {
if($this->_checkStoredProcedure($storedProcedureName) == 0) return ['error' => 'Stored Procedure does not exits'];
$pdo = \DB::connection($this->connection)->getPdo();
$parametersString = '';
$parameterCount = count($parameters);
// Dynamic Paramter String
if($parameterCount){
// Loop Parameters and add ? to parametersString
for($i = 0;$i < $parameterCount; $i++) {
$parametersString .= '?';
if($i+1 < $parameterCount) $parametersString .= ',';
}
}
$callString = "CALL $storedProcedureName($parametersString)";
$statement=$pdo->prepare($callString);
if($parameterCount) {
$pIndex = 1;
for($i = 0;$i < $parameterCount; $i++) {
$paramValue = $parameters[$i];
$statement->bindValue($pIndex,$paramValue,$this->_PDODataType($paramValue));
$pIndex++;
}
}
$statement->execute();//$query->execute(array($bindings ));
$pdoDataResults = array();
do {
$rowset = $statement->fetchAll(\PDO::FETCH_ASSOC);
if ($rowset) {
array_push($pdoDataResults,$rowset);
}
} while ($statement->nextRowset());
return $pdoDataResults;
}
private function _checkStoredProcedure($procedureName) {
$check = \DB::connection($this->connection)
->table("information_schema.routines")
->where("SPECIFIC_NAME","=",$procedureName)
->select("SPECIFIC_NAME")
->first();
return count($check);
}
private function _PDODataType($value) {
if( is_null($value) ) return \PDO::PARAM_NULL;
if( is_bool($value) ) return \PDO::PARAM_BOOL;
if( is_int($value) ) return \PDO::PARAM_INT;
if( is_object($value) ) return \PDO::PARAM_LOB;
return \PDO::PARAM_STR;
}
}
@rodion-arr
Copy link

Can I make a Composer package based on your code?

@tommyready
Copy link
Author

tommyready commented May 26, 2020 via email

@rodion-arr
Copy link

@tommyready
Copy link
Author

Very nice.

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