Zap
Documentation / Data layer

Models

Models keep database access in one place. Extend BaseModel to reuse the shared PDO connection and query helpers, then call model methods from controller actions instead of spreading SQL throughout your routes.

Create a model

Generate a model from the project root. The command creates a class under app/Models using the Zap\App\Models namespace.

php console make:model Post

The generated model extends BaseModel, declares a table name, and includes an example query method.

<?php

namespace Zap\App\Models;

use Zap\Core\Base\BaseModel;

final class Post extends BaseModel
{
 protected string $table = 'posts';

 public function all(): array
 {
 return $this->db()->select('SELECT * FROM `' . $this->table . '`');
 }
}
The $table property is a convention used by your model. It is not read automatically by BaseModel, so pass the table name to helpers such as create(), read(), update(), and delete() unless you wrap them in model methods.

Understand the model layer

BaseModel is a thin database gateway, not an active-record ORM. It does not manage relationships, events, or timestamps for you. It gives each model a lazy database connection and small query helpers that you can compose into domain-specific methods.

  • db() returns the shared Zap\Core\Db\Database instance and opens the connection on first use.
  • builder() returns a Zap\Core\Db\QueryBuilder for composing a query.
  • create($table, $data) inserts a row and returns true or false.
  • read($callback, $table, $where, $options) runs a select and calls a Database fetch method such as fetchAll or fetchArray.
  • update($table, $data, $where) and delete($table, $where) return true or false.
  • countData($table, $where, $options) returns the number of matching rows.

The connection uses the values in config/database.php, which read the DB_* values from your .env file. Resolve a model by its short name through the application container, or by its fully qualified class name.

use Zap\App\Models\Post;

$posts = model('Post');
$posts = model(Post::class); // Also valid

// Inside a controller that extends BaseController:
$posts = $this->model('Post');
The model() helper only resolves classes inside the Zap\App\Models namespace. Use the container directly with app(Post::class) when you need a different location.

Read records

Add focused methods to the model so controllers do not need to know the SQL. The read() helper accepts a fetch callback, a table, a where clause, and select options such as order, limit, and offset.

final class Post extends BaseModel
{
 protected string $table = 'posts';

 public function all(): array
 {
 return $this->read('fetchAll', $this->table, [], [
 'order' => 'id DESC',
 ]);
 }

 public function find(int $id): array|false
 {
 return $this->read('fetchArray', $this->table, [
 'id' => $id,
 ]);
 }

 public function latest(int $limit = 10): array
 {
 return $this->read('fetchAll', $this->table, [
 'status' => 'published',
 ], [
 'order' => 'created_at DESC',
 'limit' => $limit,
 ]);
 }

 public function countPublished(): int
 {
 return $this->countData($this->table, [
 'status' => 'published',
 ]);
 }
}

For joins or database-specific SQL, use the connection directly. Always pass dynamic values through the parameter array.

public function withAuthors(): array
{
 return $this->db()->select(
 'SELECT posts.*, users.name AS author_name
 FROM posts
 LEFT JOIN users ON users.id = posts.user_id
 WHERE posts.status = :status
 ORDER BY posts.created_at DESC',
 ['status' => 'published']
 );
}

Build queries safely

QueryBuilder returns an array containing the SQL string and its bound parameters. Pass both to Database::query(), select(), or another fetch method.

use Zap\Core\Db\QueryBuilder;

$query = QueryBuilder::select(
 'posts',
 ['id', 'title', 'created_at'],
 [
 'status' => 'published',
 'views' => ['>=', 100],
 'title%' => 'zap',
 ],
 [
 'order' => 'created_at DESC',
 'limit' => 20,
 'offset' => 0,
 ]
);

$posts = $this->db()->select($query['sql'], $query['params']);
  • A plain value uses equality: ['status' => 'published'].
  • An array supplies an operator and value: ['views' => ['>=', 100]].
  • A key ending in % becomes a LIKE search: ['title%' => 'zap'].
  • Use ['id' => ['IN', [1, 2, 3]]], ['deleted_at' => null], or the _or key for grouped conditions.
  • options['join'] accepts join definitions in the form [table, leftColumn, rightColumn, type].
Table and column names are validated by QueryBuilder; values are always bound. Never concatenate request input into a SQL string, even when using raw db()->select() calls.

Write records

Wrap inserts and updates in model methods so field names and defaults stay in one place. The create(), update(), and delete() helpers return a boolean result.

final class Post extends BaseModel
{
 protected string $table = 'posts';

 public function createPost(array $data): string|false
 {
 $payload = array_intersect_key($data, array_flip([
 'title',
 'body',
 'status',
 ]));

 $payload['created_at'] = date('Y-m-d H:i:s');

 return $this->db()->insert($this->table, $payload);
 }

 public function updatePost(int $id, array $data): bool
 {
 $payload = array_intersect_key($data, array_flip([
 'title',
 'body',
 'status',
 ]));

 if ($payload === []) {
 return false;
 }

 return $this->update($this->table, $payload, ['id' => $id]);
 }

 public function deletePost(int $id): bool
 {
 return $this->delete($this->table, ['id' => $id]);
 }
}
  • db()->insert($table, $data) returns the last insert ID, or false on failure.
  • db()->update($table, $data, $where) and db()->delete($table, $where) return the number of affected rows.
  • BaseModel::create() is convenient when you only need a success flag; use db()->insert() when the new ID is needed.
  • update() and delete() require a non-empty where clause to prevent accidental full-table changes.

Use models in controller actions

Point routes at controller actions, resolve the model, validate the request, and return a response. The example below uses the Post methods defined above.

use Zap\Core\Http\Route;

Route::get('/posts', 'PostController@index')->name('posts.index');
Route::get('/posts/{id}', 'PostController@show')->name('posts.show');
Route::post('/posts', 'PostController@store')->name('posts.store');
Route::put('/posts/{id}', 'PostController@update')->name('posts.update');
Route::delete('/posts/{id}', 'PostController@destroy')->name('posts.destroy');

Read actions resolve the model and pass the result to a view. Keep the model call in the action rather than putting database logic in the Blade template.

<?php

namespace Zap\App\Controllers;

use Zap\Core\Base\BaseController;
use Zap\Core\Http\Request;
use Zap\Core\Http\Response;
use Zap\Core\Utils\Security;

final class PostController extends BaseController
{
 public function index(): Response
 {
 $posts = $this->model('Post')->latest();

 return $this->view('pages.posts.index', [
 'title' => 'Posts',
 'posts' => $posts,
 ]);
 }

 public function show(int $id): Response
 {
 $post = $this->model('Post')->find($id);

 if ($post === false) {
 return $this->text('Post not found.', 404);
 }

 return $this->view('pages.posts.show', [
 'title' => $post['title'],
 'post' => $post,
 ]);
 }
}

State-changing actions validate the CSRF token before writing. Validate and authorize the submitted values, then pass only allowed fields to the model.

public function store(Request $request): Response
{
 if (!Security::get_instance()->validate_request(true)) {
 return $this->text('Invalid CSRF token.', 403);
 }

 $title = trim((string) $request->input('title', ''));

 if ($title === '') {
 return $this->text('Title is required.', 422);
 }

 $id = $this->model('Post')->createPost([
 'title' => $title,
 'body' => (string) $request->input('body', ''),
 'status' => 'draft',
 ]);

 if ($id === false) {
 return $this->text('Could not create post.', 500);
 }

 return $this->redirect(route('posts.show', ['id' => $id]));
}

public function update(Request $request, int $id): Response
{
 if (!Security::get_instance()->validate_request(true)) {
 return $this->text('Invalid CSRF token.', 403);
 }

 $title = trim((string) $request->input('title', ''));

 if ($title === '') {
 return $this->text('Title is required.', 422);
 }

 $updated = $this->model('Post')->updatePost($id, [
 'title' => $title,
 'body' => (string) $request->input('body', ''),
 ]);

 return $this->json(['updated' => $updated]);
}

public function destroy(int $id): Response
{
 if (!Security::get_instance()->validate_request(true)) {
 return $this->text('Invalid CSRF token.', 403);
 }

 $deleted = $this->model('Post')->deletePost($id);

 return $this->json(['deleted' => $deleted]);
}
The controller is responsible for request validation and authorization. A model method should assume it received validated data and should restrict the columns it writes.

Model safety

  • Bind every dynamic value through parameters; never interpolate request data into SQL.
  • Allowlist writable fields before insert or update to avoid mass-assignment mistakes.
  • Validate input and authorize the current user before calling a write method.
  • Validate the CSRF token in every POST, PUT, PATCH, and DELETE action, as shown in the Security guide.
  • Use $this->db()->getPDO() for transactions when a request changes more than one row.
  • Keep table names and column names free of user input; QueryBuilder validates identifiers for that reason.
$pdo = $this->db()->getPDO();
$pdo->beginTransaction();

try {
 $orderId = $this->db()->insert('orders', [
 'user_id' => $userId,
 'status' => 'pending',
 ]);

 if ($orderId === false) {
 throw new RuntimeException('The order could not be created.');
 }

 $this->db()->insert('order_items', ['order_id' => $orderId]);

 $pdo->commit();
} catch (Throwable $exception) {
 $pdo->rollBack();
 throw $exception;
}

For the table definition, generate a migration and run it before using the model:

php console make:migration create_posts_table
php console migrate:start
Next: handle request data in controllers

Read input, validate it, and return JSON, text, redirects, or rendered views.

Controllers guide