by K8CTR

Posted Monday, March 3, 2014 6:04 PM

I needed a PHP implementation of LINQ to parse some seemingly arbitrary SOAP API response objects by avoiding if(method_exists()) and if(is_array()) then foreach(){if(is_object){}}. So I thought I'd share my tiny introduction to PHPLinq.

$names = array("APPLE", "BIRD", "CAT", "DOG", "EGG", "FISH", "GOAT", "HAM", "ICE", "JAM", "KOALA", "LIZARD");
// Easy:
$resultsA = from('$name')
            ->where('$name => (strpos($name, "A") !== FALSE)')

$resultsB = from('$name')

$resultsC = from('$name')
            ->orderBy('$name => $name')

$resultsD = from('$name')

$resultsE = from('$name')
// Ooo, nice:
$names[] = "LIZARD";
$resultsF = from('$name')
            ->where('$name => (strpos($name, "A") !== FALSE)')
            ->distinct('$name => $name')
            ->orderBy('$name => $name')
            ->thenByDescending('$name => count($name)')
            ->select('new { "name" => $name }');

$resultsG = from('$name')
            ->where('$name => (strpos($name->name, "A") !== FALSE)')
            ->orderBy('$name => $name->name')
$names2 = array("apple", "bird", "cat", "dog", "egg", "fish", "goat", "ham", "ice", "jam", "koala", "lizard");
$resultsH = from('$name')->in($names)
                         ->on('$name, $name2 => (strcasecmp($name, $name2) == 0)')
                         ->select('$name = null, $name2 = null => $name." equal to ".$name2');

What got in the way of actually using it, was the "installation" into my existing framework. Once I found the LinqToObjects Unit Tests things started to make more sense:

$phpLinq = Config::Get('PHPLinqIncludePath');

require_once 'PHPLinq/LinqToObjects.php';

My initial production test, didn't work because I had converted the original SOAP reply object into a multi-dimensional array for convenience. PHPLinq treated the first layer of my array as a list of objects, and any subsequent arrays seem to be discarded and only the first element in the "object" array was queried/processed. This was easy enough for me to solve by not converting the original object into an array O_o. I then tested for the existence of an array within the object, build a "where" query to only pull out the objects in that array that matched the user's criteria (new feature), and sorted the result before returning it (also new feature)... nice.

Labels: , ,

0 Comments Post a Comment