Skip to content

Query collections

Greg Bowler edited this page Mar 3, 2026 · 5 revisions

A query collection is the unit we use to organise related queries.

In practice, it is either:

  • a directory containing .sql and .php query files, or
  • a single PHP class file with methods that return SQL.

SQL directory collections

If we create query/user/getById.sql, we can execute it like this:

$row = $db->fetch("user/getById", 105);

Supported separators in query names:

  • user/getById
  • user.getById
  • user\\getById

Nested collections work in the same way:

$db->fetch("admin/audit/listRecent");
$db->fetch("admin.audit.listRecent");

Working with a QueryCollection object

$userQueries = $db->queryCollection("user");

$row = $userQueries->fetch("getById", 105);
$all = $userQueries->fetchAll("listAll");
$newId = $userQueries->insert("insert", ["email" => "dev@example.com"]);

Now we can pass $userQueries into a repository class and keep access scoped to one part of the database.

You can also call queries dynamically:

$row = $userQueries->getById(105);

PHP query collections

Instead of a directory, we can use query/Product.php:

namespace App\Query;

class Product {
	public function listByCategory():string {
		return "select id, name from product where category = :category";
	}
}

Usage:

$db->fetchAll("Product/listByCategory", ["category" => "books"]);

If your namespace is not \App\Query, set it with setAppNameSpace() or setAppNamespace() on the collection.

Clone this wiki locally