Query builder
A simple query builder, with separate Model and Entity classes.
Which package you want
This one is the earlier of two answers to the same question, and it is the smaller.
For anything new, quillstack/db and quillstack/orm are what the framework uses: a query builder which binds everything it is given, entities mapped with attributes, relations which cannot be asked one query per row, and a schema worked out from the entities. This package stays for the applications already built on it.
Requirements
- PHP 8.1 or newer
ext-pdo, and the driver for your database
Installation
composer require quillstack/query-builderUsage
An entity and a model
An entity describes the table; a model reads it:
use Quillstack\QueryBuilder\Entity\Entity;
use Quillstack\QueryBuilder\Model\Model;
use Quillstack\QueryBuilder\QueryBuilder;
final class UserEntity extends Entity
{
public string $table = 'users';
}
final class User extends Model
{
public function __construct(UserEntity $entity, QueryBuilder $queryBuilder)
{
parent::__construct($entity, $queryBuilder);
}
}The entity is a constructor parameter rather than a property each model narrows the type of, because a property in PHP has the same type all the way down and a constructor may narrow what it takes.
Reading
$user = $model->find(42);
$user->entity->email;$model->select('id, email')->getQuery();
// SELECT t1.id, t1.email FROM `users` AS t1Connecting
The connection opens when the first query runs, so building a model does not need a database and neither does a request which never asks for one:
$queryBuilder = new QueryBuilder([
'host' => 'localhost',
'name' => 'shop',
'user' => 'quill',
'pass' => 'secret',
]);Technical documentation
| Class | What it is |
|---|---|
QueryBuilder | builds the statement and holds the connection |
Model\Model | one table, read through its entity |
Entity\Entity | what a table is called and what it holds |
Connection\MySqlConnector | opens the connection |
Exceptions\IncorrectColumnTypeException | select() was given neither a string nor an array |
QueryBuilder::ALIAS is t1, which is what the table is called inside the query — every column is qualified with it.
Unit tests
composer test
composer test:coverage
composer stanLicense
MIT. See LICENSE.