Documentation menu

Data

DataStores

A DataStore is a class for one database table. It reads and writes rows, builds queries, applies casts, mass-assignment rules, timestamps and soft deletes, and loads related rows. This page covers DataStores inside a Taphra application. The same classes work without the framework: see packages/db/README.md, which also lists the SchemaBuilder and SqlQuery APIs in full.

Every PHP example below runs as written, in order, against SQLite.

Contents

#

Connections

#

Connections are declared per environment in app/Config/databases.yml. A DataStore names one with its $connection property; the skeleton's AppDataStore uses app_master.

YAML
dev:
  app_master:
    type: mysql          # mysql | postgres | sqlite | mssql
    host: 127.0.0.1
    port: 3306
    name: myapp_dev
    user: root
    password: ""
    charset: utf8mb4

A SQLite connection uses type: sqlite, an empty host and port, and the database file path as name (relative paths are resolved against the app directory).

Tables are created in migrations (php taphra make:migration create_posts_table, then php taphra migrate) with the SchemaBuilder. These examples create them directly:

PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

$schema = new SchemaBuilder(DatabaseConnection::load('app_master'));
foreach (['comments', 'posts', 'users'] as $table) {
    $schema->dropIfExists($table);
}
$schema->create('users', function ($t) {
    $t->id();
    $t->string('name', 100);
    $t->string('email')->unique();
    $t->string('role', 20)->default('author');
});
$schema->create('posts', function ($t) {
    $t->id();
    $t->integer('user_id');
    $t->string('title');
    $t->text('body')->nullable();
    $t->string('status', 20)->default('draft');
    $t->boolean('is_featured')->default(false);
    $t->integer('views')->default(0);
    $t->text('meta')->nullable();
    $t->timestamps();
    $t->softDeletes();
});
$schema->create('comments', function ($t) {
    $t->id();
    $t->integer('post_id');
    $t->text('body');
    $t->boolean('approved')->default(false);
});

Defining a DataStore

#

DataStores live in app/DataStores/, in the App\DataStores namespace, and extend AppDataStore.

PHP
namespace App\DataStores;

use Taphra\DataStoreQueryBuilder;
use Taphra\Traits\SoftDeletes;
use Taphra\Traits\Timestamps;

class UserDataStore extends AppDataStore
{
    public $objectName = 'users';                 // the table
    protected $fillable = ['name', 'email'];      // accepted from input
}

class PostDataStore extends AppDataStore
{
    use Timestamps;     // created_at / updated_at
    use SoftDeletes;    // deleted_at

    public $objectName = 'posts';
    protected $fillable = ['user_id', 'title', 'body', 'status', 'meta'];
    protected $casts = [
        'is_featured' => 'bool',
        'views'       => 'int',
        'meta'        => 'json',
    ];

    public function scopePublished(DataStoreQueryBuilder $q): DataStoreQueryBuilder
    {
        return $q->where('status', 'published');
    }

    public function comments()
    {
        return $this->hasMany(CommentDataStore::class, 'post_id');
    }

    public function author()
    {
        return $this->belongsTo(UserDataStore::class, 'user_id');
    }
}

class CommentDataStore extends AppDataStore
{
    public $objectName = 'comments';
    protected $fillable = ['post_id', 'body'];
}

$connection and $objectName must be public. The primary key is read from the table; declare public $primaryKey = 'id'; (or ['post_id', 'tag_id']) for tables or views without one.

php taphra make:crud Post --table=posts writes a DataStore, a FormRequest, an ApiResource and a CrudController for a table.


Creating, reading, updating, deleting

#
PHP
use App\DataStores\CommentDataStore;
use App\DataStores\PostDataStore;
use App\DataStores\UserDataStore;

// create() fills through $fillable, inserts, and returns the stored row.
$alice = UserDataStore::create(['name' => 'Alice', 'email' => '[email protected]']);
$post  = PostDataStore::create(['user_id' => $alice['id'], 'title' => 'Hello', 'status' => 'published', 'meta' => ['color' => 'blue']]);

// insert() / save() take an array and return the new primary key. save() runs
// the beforeSave() hooks (casts, Timestamps); insert() does not.
$ds = new PostDataStore();
$id = $ds->insert(['user_id' => $alice['id'], 'title' => 'Draft one']);
$ds->save(['user_id' => $alice['id'], 'title' => 'Draft two']);
(new CommentDataStore())->insert(['post_id' => $post['id'], 'body' => 'First!']);

// Read
$one   = PostDataStore::findById($post['id']);                     // ?DataStoreRow
$first = PostDataStore::firstWhere(['status' => 'published']);
$all   = PostDataStore::all();                                      // DataStoreCollection
$some  = $ds->find(['status' => 'draft'], 10, 0, 'id', 'DESC');     // conditions, limit, offset, order column, direction
$n     = $ds->findCount(['status' => 'draft']);
$found = $ds->exists(['title' => 'Hello']);

// Update through the row (only changed columns, updated_at set)...
$one->title = 'Hello, world';
$one->save();

// ...by key...
$ds->update(['id' => $id], ['title' => 'Draft one (edited)']);

// ...or every matching row.
$ds->update(['status' => 'draft'], ['body' => 'Not written yet']);

// Delete (soft delete here: PostDataStore uses SoftDeletes)
$ds->delete(['id' => $id]);
PostDataStore::firstWhere(['title' => 'Draft two'])->delete();

// Insert or update on a unique key
(new UserDataStore())->upsert(['name' => 'Alice A.', 'email' => '[email protected]'], ['email']);

// findOrFail() throws Taphra\Db\RecordNotFoundException; a Taphra app answers it with a 404.
try {
    $ds->findOrFail(['id' => 999]);
} catch (\Taphra\Db\RecordNotFoundException $e) {
}

// Several writes in one transaction (all DataStores on a connection share one handle)
PostDataStore::transaction(function () use ($alice) {
    $p = PostDataStore::create(['user_id' => $alice['id'], 'title' => 'Atomic', 'status' => 'draft']);
    (new CommentDataStore())->insert(['post_id' => $p['id'], 'body' => 'Same transaction']);
});

Batch writes: insertBatch($rows) and upsertBatch($rows, $conflictColumns) send many rows per statement. The active-record style (resetRecord(), fill(), save(), read($id), get($field)) is described in the package README.


The query builder

#

Static calls start a builder; (new PostDataStore())->query() returns one too.

PHP
use App\DataStores\PostDataStore;

$posts = PostDataStore::where('status', 'published')
    ->where('views', '>=', 0)
    ->whereIn('user_id', [1, 2])
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();                                   // DataStoreCollection

$latest   = PostDataStore::where('status', 'published')->orderBy('id', 'desc')->first();
$count    = PostDataStore::where('status', 'published')->count();
$views    = PostDataStore::where('user_id', 1)->sum('views');
$titles   = PostDataStore::where('user_id', 1)->pluck('title');
$matching = (new PostDataStore())->query()->whereContains(['title', 'body'], 'hello')->get();
$perUser  = (new PostDataStore())->query()->selectRaw('user_id, COUNT(*) AS n')->groupBy('user_id')->get();
$long     = PostDataStore::whereRaw('LENGTH(title) > ?', [3])->get();
$blue     = PostDataStore::jsonPath('meta', 'color', '=', 'blue')->get();
$active   = PostDataStore::whereHas('comments', 'post_id')->get();
$counted  = PostDataStore::withCount('comments', 'post_id')->get();

(new PostDataStore())->query()->orderBy('id')->chunk(100, function ($batch) {
    // ...
});

echo PostDataStore::where('status', 'published')->toSql();   // for logs and debugging

On a grouped query (groupBy() or having()), count() counts the groups, and sum(), avg(), min() and max() throw a DbException rather than return one group's value: select the aggregate with selectRaw() and read one value per group with get(), as $perUser does above.

The full list of builder methods is in the package README.


Rows and collections

#
PHP
use App\DataStores\PostDataStore;

$posts = PostDataStore::all();
$post  = $posts->first();

$post['title'];              // array access
$post->title;                // property access
$post->title = 'Renamed';
$post->isDirty('title');     // true
$post->getDirty();           // ['title' => 'Renamed']
$post->getOriginal('title');
$post->refresh();            // reload, dropping the change
$post->only(['id', 'title']);
$post->except(['body']);
$post->toArray();
json_encode($post);

count($posts);
$posts->isEmpty();
$posts->filter(fn ($p) => $p['views'] > 0);
$posts->map(fn ($p) => $p['title']);
$posts->keyBy('id');
$posts->each(function ($p) {});
$posts->toArray();           // array of DataStoreRow
$posts->toJson();            // same as json_encode($posts): a JSON list of the rows

Casts

#

$casts converts columns when rows are read and when a row is saved with save() (the active record, an array passed to save($data), or a DataStoreRow). insert(), update() and upsert() do not apply them (on an SQL connection a PHP array is still stored as JSON). Types: bool/boolean, int/integer, float/double, string, array/json (decoded to an array), object (decoded to an object), datetime (a DateTime).

PHP
use App\DataStores\PostDataStore;

$post = PostDataStore::firstWhere(['title' => 'Hello, world']);
var_dump($post['is_featured']);     // bool(false)
var_dump($post['meta']['color']);   // string(4) "blue"

Timestamps and soft deletes

#

Timestamps sets created_at on insert and updated_at on every save: the active record, an array passed to save($data), and DataStoreRow::save(). A new row gets both, also when its record was filled without resetRecord() first. insert() and update() run no hooks, so they do not set them. Rename the columns with protected $createdAtColumn / $updatedAtColumn, or store Unix times with protected $timestampFormat = 'unix';. Its beforeSave() then calls the parent class's beforeSave(), so casts (an object or array column stored as JSON) and your base class's hook still run.

SoftDeletes makes delete() set deleted_at. Every read (find(), findCount(), exists(), the query builder's get(), count(), sum(), paginate()) leaves deleted rows out.

PHP
use App\DataStores\PostDataStore;

$ds = new PostDataStore();
$ds->delete(['title' => 'Atomic']);
$ds->findCount(['title' => 'Atomic']);                    // 0
$ds->withTrashed()->findCount(['title' => 'Atomic']);     // 1
$ds->onlyTrashed()->find();                               // just the deleted rows
$ds->restore(['title' => 'Atomic']);                      // deleted_at back to NULL
$ds->forceDelete(['title' => 'Atomic']);                  // a real DELETE

withTrashed() and onlyTrashed() apply to the next query run on that DataStore instance, or to a whole query-builder query started from it: $ds->withTrashed()->query()->paginate(20).


Relations and eager loading

#

hasMany(), hasOne(), belongsTo() and belongsToMany() declare relations. Name the related DataStore by class (CommentDataStore::class) or by short name ('comment' finds CommentDataStore in the same namespace, then the global one). DataStoreCollection::load() fetches a relation for every row of a collection in one query, so a list page does not run one query per row:

PHP
use App\DataStores\PostDataStore;

$posts = PostDataStore::published()->get();
$posts->load('comments', 'author');                  // two queries in total

foreach ($posts as $post) {
    $comments = $post->getRelation('comments');      // DataStoreCollection
    $author   = $post->getRelation('author')?->first();
    $post->relationLoaded('comments');               // true
}

load() supports hasMany, hasOne and belongsTo. Calling a relation method on a DataStore only declares the relation; it does not run a query.

Two more relation helpers return rows directly (call them from a method on the DataStore, after read()):

  • hasManyVia($targetClass, $pivotClass, $firstKey, $secondKey): rows two hops away, for example a country's posts through its users.
  • polymorphicChildren($relatedClass, $morphName), polymorphicChild() and polymorphicParent($morphName): rows linked by <morph>_type and <morph>_id columns. Register the type values first with DataStore::registerPolymorphicTypes(['post' => PostDataStore::class]); class names are never stored.

Scopes

#

A public method named scope<Name>() becomes a static entry point. If its first parameter is a DataStoreQueryBuilder, it receives a fresh builder; other parameters come from the call.

PHP
namespace App\DataStores;

use Taphra\DataStoreQueryBuilder;

class ArticleDataStore extends AppDataStore
{
    public $objectName = 'posts';

    public function scopePublished(DataStoreQueryBuilder $q): DataStoreQueryBuilder
    {
        return $q->where('status', 'published');
    }

    public function scopeByUser(DataStoreQueryBuilder $q, int $userId): DataStoreQueryBuilder
    {
        return $q->where('user_id', $userId);
    }

    public function scopeRecent(): DataStoreQueryBuilder
    {
        return $this->query()->orderBy('created_at', 'desc');
    }
}
PHP
use App\DataStores\ArticleDataStore;

$a = ArticleDataStore::published()->orderBy('id')->get();
$b = ArticleDataStore::byUser(1)->count();
$c = ArticleDataStore::recent()->limit(5)->get();

A scope must return a DataStoreQueryBuilder; anything else throws a DataStoreException.


Global filters

#

A filter is a named condition added to every query-builder query on a class. Filters can be skipped one by one.

PHP
use App\DataStores\PostDataStore;

PostDataStore::addFilter('published', fn ($q) => $q->where('status', 'published'));

$visible = PostDataStore::where('user_id', 1)->get();            // published rows only
$all     = PostDataStore::unfiltered()->get();                   // every filter skipped
$drafts  = PostDataStore::unfiltered('published')->where('status', 'draft')->get();

PostDataStore::removeFilter('published');
PostDataStore::flushFilters();

Filters apply to the query builder (where(), get(), count(), sum(), paginate() and the rest), not to find(), findById() or all().


Hooks

#

Override these public methods on a DataStore. Call the parent method in beforeSave() and afterFind(): casts (and the Timestamps and SoftDeletes traits) work through them.

Method Called Return
beforeFind(mixed &$conditions): bool before find() and findCount(), and once per query-builder query false cancels the query
afterFind(mixed $conditions, mixed &$result): void after find(), on the raw rows
beforeSave(mixed $data): bool before save() inserts or updates. The values being saved are in $this->activeRecord, also for save($data) with an array, and what the hook changes there is saved false cancels the save: nothing is written, afterSave() does not run, save() returns false and create() throws Taphra\Db\DataStoreException
afterSave(mixed $data, mixed $result): void after save()
beforeDelete(mixed $criteria): bool before delete() false cancels the delete
afterDelete(mixed $criteria, mixed $result): void after delete()
PHP
namespace App\DataStores;

class AuditedPostDataStore extends AppDataStore
{
    public $objectName = 'posts';
    public array $log = [];

    public function beforeDelete(mixed $criteria): bool
    {
        $this->log[] = 'deleting';
        return true;
    }

    public function afterSave(mixed $data, mixed $result): void
    {
        $this->log[] = 'saved';
    }
}
PHP
use App\DataStores\AuditedPostDataStore;

$audited = new AuditedPostDataStore();
$audited->save(['user_id' => 1, 'title' => 'Audited']);
$audited->delete(['title' => 'Audited']);
// $audited->log === ['saved', 'deleting']

Observers

#

Observers react to the same events from outside the DataStore class: any object with afterSave(), afterDelete() and/or afterFind() methods. They run after the hooks, in registration order, and are kept per DataStore class.

PHP
use App\DataStores\CommentDataStore;

class CommentCounter
{
    public int $saved = 0;

    public function afterSave(mixed $data, mixed $result): void
    {
        $this->saved++;
    }
}

$counter = new CommentCounter();
CommentDataStore::observe($counter);              // an instance, or a class name
(new CommentDataStore())->save(['post_id' => 1, 'body' => 'Observed']);
// $counter->saved === 1
CommentDataStore::flushObservers();               // e.g. in a test's setUp()

Register observers once at boot, for example in a service provider's boot() method.


Pagination

#
PHP
use App\DataStores\PostDataStore;
use Taphra\Http\ListQuery;

$page = PostDataStore::paginate(20);                       // reads ?page
$page = PostDataStore::where('status', 'published')->paginate(20, 1);
$page->items;        // rows on this page
$page->total;        // rows on every page
$page->lastPage;
$page->hasMore;
$page->meta();       // the numbers only, for an API response

// An index action: ?search=, ?sort=, ?dir= and ?page= from the request
$list = ListQuery::fromRequest()
    ->searchable(['title', 'body'])
    ->sortable(['title', 'created_at'], 'created_at', 'desc')
    ->paginate(new PostDataStore(), 20);

In a view, $html->pagination($list, '/posts') renders the page links. CrudController builds JSON index, show, store, update and destroy actions on top of these.


Input safety

#
  • Values are bound as ? parameters everywhere: where(), array conditions (find(['email' => $email])), Criteria, and the array conditions of update() and delete().
  • Condition keys, orderBy(), groupBy() and JSON paths accept column names only; operators come from a fixed list; LIMIT and OFFSET are integers.
  • String conditions (find('views > 10')), where('raw SQL') and the *Raw() methods are SQL: write them in code, never from request data.
  • Condition arrays need column-name keys; an integer key may only carry a Criteria object.
  • findById() rejects array ids such as ?id[]=; a composite id must name exactly the primary-key columns.
  • With $fillable declared, a primary key in save($data) that is not fillable is dropped: the call inserts instead of updating that row. Update by key with update(['id' => $id], $data).
  • $fillable / $guarded filter fill(), create(), and (when the DataStore declares either) the data passed to save(), insert(), update() and upsert(). Values set on a row or through forceFill() are not filtered.
  • $fillable names are matched exactly. $guarded names are matched in any case (MySQL, MariaDB and SQLite read ROLE as the column role), and with $guarded a key that is not a column spelled as in the table's schema is dropped.

Other backends

#

This page covers SQL databases (SQLite, MySQL/MariaDB, PostgreSQL; SQL Server statements are generated but not tested against a server). The package also ships RedisConnection and an experimental MongodbConnection, which are not covered here. DataStores on MongoDB are not supported in 1.0: use MongodbConnection directly, and expect it to change. The query builder, relations, SchemaBuilder and SqlQuery are SQL only.