Instead of embedding the query text in the Models, I've got a separate file for each query, and store these files in a directory called (oddly enough) Queries. If a particular Model requires access to a query, it reads in the appropriate file. This allows reuse of queries across multiple Models. (See the Filesystem.png attachment)
Now, a particular Model method looks something like this:
// Gets the information about the users latest project
final public function GetUsersLatestProject()
{
$index = 'GetUsersLatestProject';
$bound_values = array(
'UserID' => User::ID(),
);
return PSFetch::AssocUnique($index, $bound_values);
}
... which is pretty lightweight and easy to read. You may not know what each of my called methods is doing, but the program flow is pretty obvious:
- Set the index
- Set the bound values
- Fetch a unique associative array from the indexed query, passing the bound values
And for reference, here is the query file for GetUsersLatestProject:
SELECT
{SQL_PROJECTS}.`ID`
FROM {SQL_PROJECTS}
INNER JOIN {SQL_PROJECT_OWNERS} ON {SQL_PROJECT_OWNERS}.`ProjectID` = {SQL_PROJECTS}.`ID`
WHERE {SQL_PROJECT_OWNERS}.`UserID` = :UserID
AND {SQL_PROJECT_OWNERS}.`IsOwner` = 1
AND {SQL_PROJECTS}.`CreatedAt` = (
SELECT
MAX(`CreatedAt`)
FROM {SQL_PROJECTS}
)
...and to explain this file, anything in curly braces gets preg_replaced via templating, and anything preceded with a : character is a bound value.
So now that I've explained a little, here is the problem:
I'm a fraction of the way through fleshing out the entire first draft of my application, and I'm already up to 29 separate queries. So, the Queries directory is starting to get, let's say, unmanageable. It's an eyesore really. The reason I've stored queries separately is so that multiple Models can access the same query, and therefore any query changes that need to be made due to DB schema changes need only be applied once to affect the entire application.
I'm now leaning towards defining queries within the Models, which I've seen other programmers on this forum do, such as Dormilich. Can anyone give advice as to whether I should be changing my Model system and put the queries inside the Models? The direct fallout of this is that query strings are no longer centralised.
P.S. I've already thought of having parent Models that have the shared queries, the problem is I might have one Model that uses query A and B, another Model that uses A and C, and a third Model that uses B and C. Due to single-class inheritance, I can't comprehensively push all shared query methods up the class tree

New Topic/Question
Reply



MultiQuote





|