-
-
Notifications
You must be signed in to change notification settings - Fork 3
Query collections
A query collection is the unit we use to organise related queries.
In practice, it is either:
- a directory containing
.sqland.phpquery files, or - a single PHP class file with methods that return SQL.
If we create query/user/getById.sql, we can execute it like this:
$row = $db->fetch("user/getById", 105);It's recommended to use the / character to separate directories, but the following separators are supported:
user/getByIduser.getByIduser\\getById
Nested collections work in the same way:
$db->fetch("admin/audit/listRecent");
$db->fetch("admin.audit.listRecent");$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, enforcing encapsulation to the database.
Warning
It is bad practice to embed SQL within strings, and the below is only made possible so that Query classes can utilise the features of PHP.GT/SqlBuilder - the functionality is maintained separately to keep the Database layer clean and minimal.
Instead of storing SQL files in a named directory, we can use a PHP class. For example, 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.
In the next section we will jump in to building queries with Parameter binding.
PHP.GT/Database is a separately maintained component of PHP.GT/WebEngine.