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') ->in($names) ->where('$name => (strpos($name, "A") !== FALSE)') ->select('$name'); var_dump($resultsA); $resultsB = from('$name') ->in($resultsA) ->concat(array("MARS")) ->select('$name'); var_dump($resultsB); $resultsC = from('$name') ->in($resultsB) ->orderBy('$name => $name') ->reverse() ->select('$name'); var_dump($resultsC); $resultsD = from('$name') ->in($resultsC) ->count(); var_dump($resultsD); $resultsE = from('$name') ->in($resultsC) ->skip(1) ->take(2) ->select('$name'); var_dump($resultsE); // Ooo, nice: $names[] = "LIZARD"; $resultsF = from('$name') ->in($names) ->where('$name => (strpos($name, "A") !== FALSE)') ->ofType('string') ->distinct('$name => $name') ->orderBy('$name => $name') ->thenByDescending('$name => count($name)') ->select('new { "name" => $name }'); var_dump($resultsF); $resultsG = from('$name') ->in($resultsF) ->where('$name => (strpos($name->name, "A") !== FALSE)') ->orderBy('$name => $name->name') ->first(); var_dump($resultsG); $names2 = array("apple", "bird", "cat", "dog", "egg", "fish", "goat", "ham", "ice", "jam", "koala", "lizard"); $resultsH = from('$name')->in($names) ->join('$name2') ->in($names2) ->on('$name, $name2 => (strcasecmp($name, $name2) == 0)') ->select('$name = null, $name2 = null => $name." equal to ".$name2'); var_dump($resultsH);
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'); set_include_path(get_include_path().PATH_SEPARATOR.$phpLinq); 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.