Examples
A set of examples are contained in the runnable example/ directory and the PHPUnit helper queries.
Running the repository example
From the repository root:
php example/01-simple-select.php
That example shows the smallest class-based SelectQuery setup.
Example index
- example/01-simple-select.php
A simple
SelectQuerysubclass. test/phpunit/Helper/Query/SelectExample.phpA baseselectquery with a reusablewhereclause.test/phpunit/Helper/Query/SelectExampleExtendWhere.phpExtending a base query to add one more condition.test/phpunit/Helper/Query/SelectExampleExtendComplex.phpNested conditions with grouped boolean logic.test/phpunit/Helper/Query/SelectExampleSubquery.phpA select containing a subquery.test/phpunit/Helper/Query/InsertExample.phpInsert with associativeset()syntax.test/phpunit/Helper/Query/InsertSelectInlineExample.phpinsert ... select ....test/phpunit/Helper/Query/UpdateExample.phpUpdate with short placeholder assignment syntax.test/phpunit/Helper/Query/DeleteExample.phpA straightforward delete query.test/phpunit/Helper/Query/Table/CreateTableExample.phpCreate-table query class.test/phpunit/Helper/Query/Table/AlterTableExample.phpAlter-table query class.test/phpunit/Helper/Query/Table/DropTableExample.phpDrop-table query class.
A few patterns worth copying
Base query plus subclass
This is the most important pattern in the library:
use GT\SqlBuilder\Query\SelectQuery;
class StudentSelect extends SelectQuery {
public function select():array {
return ["id", "name", "dateOfBirth"];
}
public function from():array {
return ["student"];
}
public function where():array {
return ["deletedAt is null"];
}
}
class StudentWithTestFlagSelect extends StudentSelect {
public function where():array {
return array_merge(parent::where(), [
"test = 123",
]);
}
}
Inline builder
This is the equivalent small-query pattern:
use GT\SqlBuilder\SelectBuilder;
$query = new SelectBuilder();
$query->select("id", "email")
->from("user")
->where("deletedAt is null")
->limit(100);
Grouped conditions
use GT\SqlBuilder\Condition\Equals;
use GT\SqlBuilder\Condition\GreaterThan;
use GT\SqlBuilder\Condition\MatchAny;
use GT\SqlBuilder\Condition\MultipleCondition;
$where = new MultipleCondition(
new MatchAny(),
new Equals("status", "active"),
new GreaterThan("score", 50),
);
Where these examples fit in a real application
In a small application, one or two builders may be enough.
In a growing application, the helper query classes in the test suite reflect the style that tends to age better:
- give queries names
- extend base queries
- keep condition logic in the query object
- keep execution somewhere else
[!NOTE] In WebEngine projects, that usually means page logic or services decide which query to use, while database execution lives in the database layer rather than in the query class itself.