Skip to content

Query builder

composer require quillstack/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

shell
composer require quillstack/query-builder

Usage

An entity and a model

An entity describes the table; a model reads it:

php
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

php
$user = $model->find(42);

$user->entity->email;
php
$model->select('id, email')->getQuery();
// SELECT t1.id, t1.email FROM `users` AS t1

Connecting

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:

php
$queryBuilder = new QueryBuilder([
    'host' => 'localhost',
    'name' => 'shop',
    'user' => 'quill',
    'pass' => 'secret',
]);

Technical documentation

ClassWhat it is
QueryBuilderbuilds the statement and holds the connection
Model\Modelone table, read through its entity
Entity\Entitywhat a table is called and what it holds
Connection\MySqlConnectoropens the connection
Exceptions\IncorrectColumnTypeExceptionselect() 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

shell
composer test
composer test:coverage
composer stan

License

MIT. See LICENSE.

Released under the MIT License.