PHP LINQ: A nice alternative

A few days ago, I was browsing through the CodePlex projects, to see if I could find something nice to try, and it happens I did. I’ve always been a defender of .NET and it was the motive of several discussions with my (not so fan of .NET) friends. One feature that I’ve always enjoyed on C# was the introduction of LINQ on .Net 3.5 which I believe is one of those life changers of the language.

For those of you who hate .NET or just don’t care about it, LINQ is a powerful way to access/query your data through a set of extension methods created on the IEnumerable interface. For those of you who’ve never heard of it, you can do amazing things like this:

var aCollection = new List<AnySortOfClass>();

var query = from item in aCollection 
   where item.APropertyName == “Nice!!” 
   select item;

foreach (var item in query )
 Console.WriteLine(“Found an item: ” + item.Name);

This is a pretty neat stuff to have when programming, at least you can kiss goodbye to all the nasty for loops (or foreach loops) looping into an array just to filter data. The idea of taking the SQL approach into other programming languages, at least for performing data related tasks is very reasonable one, so I believed that LINQ would be conceived for at least a few other languages.

Due to the fact of LINQ heavy use of anonymous types and lambdas (supported on PHP until 5.3, at least directly, before we could use create_function() ), I didn’t had much hope for a PHP version of LINQ to show up, then I found PHP LINQ, a project hosted in CodePlex and maintained by Martin Balliauw.

After browsing for a couple minutes the source code and the examples, I have to say, that PHP LINQ does have some potential. For instance, there is a Zend_Db_Table adapter for those who use Zend framework, which is kinda neat. You can do something like this:

Assuming you have a EmployeeTable (employee.php)

class EmployeeTable extends Zend_Db_Table {
    // table name
 protected $_name = 'employees'; 
    protected $_primary = 'Id';

You can now perform this query:

$employeeTable = new EmployeeTable(array('db' => $db));

$result = from('$employee')
 ->in( $employeeTable )
 ->where('$employee => strlen($employee->Name) < 5')
foreach ($result as $employee){
 // do something with $employee...

I think this is a rather nice way to work around queries for the database. Anyways, will try to do on my free time (which is kinda scarce these days) a driver for using with Propel, which is the ORM I like using!