My application uses a few very large and complex SQL queries. I don't want to have these in the classes that use them as they clutter things up. So I tried something new: storing them in a Queries
class and setting the various queries my app uses as const
variables in that class. And then, in my other classes I call the query as Db::query(Queries::queryID, array($parameter))
. This stores the clutter of the queries somewhere else, and keeps the working classes neat. This also helps keep repetition down as there are a few queries that are used by multiple classes.
Example:
abstract class Queries {
const queryID = <<<'SQL'
SELECT t.typeID, t.typeName, ROUND(greatest(0,sum(t.quantity)) * (1 + (b.wasteFactor / 100))) * ? AS quantity
FROM
(SELECT invTypes.typeid typeID, invTypes.typeName typeName, quantity
FROM invTypes, invTypeMaterials, invBlueprintTypes
WHERE invTypeMaterials.materialTypeID = invTypes.typeID AND
invBlueprintTypes.productTypeID = invTypeMaterials.typeID AND
invTypeMaterials.TypeID = ?
UNION
SELECT invTypes.typeid typeid, invTypes.typeName name, invTypeMaterials.quantity * r.quantity * - 1 quantity
FROM invTypes, invTypeMaterials, ramTypeRequirements r, invBlueprintTypes bt
WHERE invTypeMaterials.materialTypeID=invTypes.typeID AND
invTypeMaterials.TypeID =r.requiredTypeID AND
r.typeID = bt.blueprintTypeID AND
r.activityID = 1 AND
bt.productTypeID = ? AND
r.recycle = 1
) t
INNER JOIN invBlueprintTypes b ON (b.productTypeID = ?)
GROUP BY t.typeid, t.typeName
SQL;
...
}
This is working well for the most part, but I wanted to know of others' opinions on separating queries from the working classes like this. Is there a better method? Am I micromanaging this?