Wrote this little thing a few days ago. I thought it was pretty neat, anyone seen any projects using this technique?
PHP Code:
/**
* Generate dynamic sql call method used to handle method strings like
* getById, deleteById, getByNameAndDob, etc. with method arguments
* which are parsed between the instances of "and" within the string.
*
*/
public function __call($method, $args)
{
$deleteIndex = 6;
$getIndex = 3;
$index = 0;
$deletePrefix = strtolower(substr($method, 0, $deleteIndex));
$getPrefix = strtolower(substr($method, 0, $getIndex));
if($deletePrefix == 'delete')
{
$index = $deleteIndex;
}
else if($getPrefix == 'get')
{
$index = $getIndex;
}
else
{
throw new Exception("Invalid method call to '$method'");
}
$queryArguments = strtolower(substr($method, $index));
// now we need to account for 'by'
$queryArguments = substr($queryArguments, 2);
// explode by and
$argumentList = explode('and', $queryArguments);
// determine what's legal...
$possibleArgs = array_keys($this->vo->export()); // << THIS VO object is just a ValueObject and export() turns it into an array.
// this line is a little tricky. Basically it's using the two arrays ($argumentList, $possibleArgs) to see if all the arguments in $argumentList exist within $possibleArgs by getting a count of that, and comparing
$intersectionIndex = count(array_intersect($argumentList, $possibleArgs));
$argumentListCount = count($argumentList);
$tableName = $this->vo->getTableName();
if($intersectionIndex != $argumentListCount)
{
$argsToString = implode(', ', $argumentList);
throw new Exception("Nonexistent property attempted as a parameter to dynamic method '$method': $argsToString");
}
else if(count($args) != $argumentListCount)
{
$argsToString = implode(', ', $argumentList);
throw new Exception("Invalid number of parameters relative to the number of arguments defined within the method name '$method': $argsToString");
}
else if($index == $deleteIndex)
{
$sql = 'DELETE FROM ' . $tableName . ' WHERE ';
}
else if($index == $getIndex)
{
$sql = 'SELECT * FROM ' . $tableName . ' WHERE ';
}
else
{
throw new Exception("Invalid dynamic method type '$method'");
}
$where = '';
foreach($argumentList as $key => $arg)
{
$where .= "$arg = :$arg";
$where .= $argumentListCount - 1 == $key ? '' : ' AND ';
}
$setString = $sql . $where;
// USING PDO
$st = $this->db->prepare($setString);
// now go ahead and set the field values...
foreach($argumentList as $key => $arg)
{
$metaVal = MetaClass::$arg;
$type = $metaVal['pdo_param_type'];
$st->bindValue($arg, $args[$key], $type);
}
if($st->execute())
{
return $st;
}
else
{
return null;
}
}
Bookmarks