Elgg 1 is introducing a new (to elgg at least) way of executing arbitrary database queries. Basically, SQL is abstracted away into a class that can be used to construct multiple different types of query through a defined interface.
This provides two main advantages:
- The application programmer does not have to write the SQL themselves.
- It becomes considerably easier to change database back ends later down the line.
In addition, we can add free stuff like access controls etc.
From the documentation:
Query provides a framework to construct complex queries in a safer environment.
The usage of this class depends on the type of query you are executing, but the basic idea is to construct a query out of pluggable classes.
Once constructed SQL can be generated using the toString method, this should happen automatically if you pass the Query object to get_data or similar.
To construct a query, create a new Query() object and begin populating it with the various classes that define the various aspects of the query.
- You do not have to specify things in any particular order, provided you specify all required components.
- With database tables you do not have to specify your db prefix, this will be added automatically.
- When constructing your query keep an eye on the error log – any problems will get spit out here. Note also that __toString won’t let you throw Exceptions (!!!) so these are caught and echoed to the log instead.
Here is an example of a select statement:
// Construct the query
$query = new Query();
// Say which table we're interested in
// What fields are we interested in
// Add access control (Default access control uses default fields on entities table.
// Note that it will error without something specified here!
// Set a limit and offset, may be omitted.
// Specify the order, may be omitted
$query->setOrder(new OrderQueryComponent("entities", "subtype", "desc"));
// Construct a where query
// This demonstrates a WhereSet which lets you have sub wheres, a
// WhereStatic which lets you compare a table field against a value and a
// Where which lets you compare a table/field with another table/field.
new WhereStaticQueryComponent("entities", "subtype","=", 1),
new WhereQueryComponent("entities","subtype","=", "entities", "subtype")
Constructing a query out of classes in this way provides a lot of scope for expanding the functionality within a common framework, as well as providing a structured way of constructing complicated database queries.
However, if it looks too complicated, you can use about 99% of
Query‘s functionality by using the subclass
SimpleQuery, which provides methods for performing much of the standard functionality.