LINQ for PHP (Language Integrated Query for PHP)
On his blog,
Maarten Balliauw started a new class library mimicing C#'s LINQ technology.
Perhaps you have already heard of C# 3.5's "LINQ"
component. LINQ,
or Language Integrated Query, is a component inside the .NET framework which enables
you to perform queries on a variety of data sources like arrays, XML, SQL server,
… These queries are defined using a syntax which is very similar to SQL.There is a problem with LINQ though… If you start using this, you don't want
to access data sources differently anymore. Since I'm also a PHP developer,
I thought of creating a similar concept for PHP. So here's the result of a few
days coding:
Let's say we have an array of strings and want to select only the strings whose
length is < 5. The PHPLinq way of achieving this would be the following:
// Create data source
$names = array("John", "Peter", "Joe", "Patrick", "Donald", "Eric");
$result = from('$name')->in($names)
->where('$name => strlen($name) < 5')
->select('$name');
Feels familiar to SQL? Yes indeed! No more writing a loop over this array, checking
the string's length, and adding it to a temporary variable.
Read more about this and get familiar with this useful technology.


3 comments to “LINQ for PHP (Language Integrated Query for PHP)”
March 20th, 2008 at 2:19 pm
The variable in php become to database table,
March 27th, 2008 at 12:52 am
All those code within strings looks weird. And what’s about the from(‘$name’) thing? What exactly do I need this variable (is it a variable?) for?
Even if I look at the examples on the page, I don’t get why this should be more convenient than using a foreach-loop and a couple of if-statements.
I can even use objects if they extend the ArrayIterator class, so why exactly should I use PHPLinq?
April 17th, 2008 at 12:09 pm
MH:It’s great because it saves you a great deal of time. In this example it’s easy, but imagine: You have shop and a cart (saved in SESSION) – you want to select everything over 199$ and order it descending. To do so in "normal" code, you would use at least 3 cycles and a bunch of IFs. Here you would use just from(‘$item’)->in(‘$_SESSION["cart"]‘)->where(‘price > 199′)->orderbydescending(‘price’)->select() (or something simmilar – i’m not fammiliar with the syntax yet).
Really looking forward to using it