Model Documentation

Model System
Your Data Navigator

The Model class in Zenith serves as your spacecraft's data bay — a sleek, powerful system for managing entities with elegance across your application's universe.

Key Features

Built for Interstellar Reliability

Every model comes equipped with the essential systems you need for safe, efficient data operations across any scale of mission.

Active Record Pattern

Each model instance represents a single record with built-in persistence methods.

Intuitive Object-Oriented
Change Tracking

Models know when they've been modified and handle updates intelligently.

Smart Updates Dirty Checking
Automatic Timestamps

Created and modified dates are handled automatically — no manual tracking needed.

CreatedDate ModifiedDate
Safe by Design

Built-in SQL injection protection through prepared statements and parameter binding.

Prepared Parameter Binding

Core Operations Made Simple

Like a well-designed starship console, each model operation is intuitive, powerful, and designed to get you where you need to go without friction.

Navigation & Discovery

Find your data with precision across constellations
// Find a specific user by ID
$user = User::find(42);

// Count active users across the fleet
$activeCount = User::count(['status' => 'active']);

// Search for captains in the database
$captains = User::findLike('rank', '%Captain%');

// Find users by multiple IDs
$crew = User::findIn('ID', [1, 2, 3, 4]);

// Advanced filtering with conditions
$admins = User::findAll(['role' => 'admin'], 'name ASC', 10);

// Check if records exist
$exists = User::exists(['email' => '[email protected]']);

Creation & Modification

Build and update entities with elegant interface
// Launch a new entity
$user = new User(['name' => 'Captain Nova']);
$user->save();

// Check what's changed before saving
if ($user->isDirty()) {
    $changes = $user->getDirtyAttributes();
    $user->save();
}

// Smart updating with change tracking
$user->name = 'Admiral Nova';
$user->rank = 'Fleet Admiral';

// Get original values before changes
$originalName = $user->getOriginal('name');

// Refresh data from the database
$user->refresh();

Utility & Inspection

Inspect and manage your model instances
// Get primary key value
$userId = $user->getId();

// Check if it's a new record
$isNewRecord = $user->isNew();

// Check specific attribute changes
if ($user->isDirtyAttribute('rank')) {
    echo "Rank has been modified!";
}

// Convert to array for JSON APIs
$userData = $user->toArray();
echo json_encode($userData);

// Magic property access
$name = $user->name;  // Same as $user->getAttribute('name')
$user->name = 'New Name';  // Same as $user->setAttribute('name', 'New Name')

// Delete records
$user->delete();

From Blueprint to Launch

Creating your own models is as simple as extending the base Model class and defining your table configuration. Three steps to data mastery.

1
Extend the Model

Create a new class that extends the base Model class — this gives you all the core functionality.

User.php
class User extends Model
2
Define Your Table

Set the table name and primary key — these tell the model where to find its data in the database.

Configuration
protected static $table = 'users';
protected static $primaryKey = 'ID';
3
Start Navigating

Your model is ready for takeoff — find, create, update, and delete records with elegant simplicity.

Usage
$user = User::find(1);
$user->name = 'Updated';
$user->save();

Complete User Model Example

A real-world implementation showing all the essentials
<?php

namespace Zenith\Models;

use Zenith\Core\Model;

class User extends Model {
    protected static string $table = 'users';
    protected static string $primaryKey = 'ID';

    // That's it! Now you have a fully functional model
}

// Usage Examples - All these work out of the box:

// Basic find operations
$user = User::find(42);                       // Get by ID
$users = User::findAll(['status' => 'active'], 'name ASC', 10);  // Filter & sort
$admin = User::findFirst(['role' => 'admin']); // First match

// Advanced queries
$activeCount = User::count(['status' => 'active']);        // Count records
$exists = User::exists(['email' => '[email protected]']); // Check existence
$captains = User::findLike('rank', '%Captain%');           // LIKE queries
$crew = User::findIn('ID', [1, 2, 3, 4]);                // Multiple IDs

// Create new records
$newUser = new User([
    'name' => 'Captain Nova',
    'email' => '[email protected]',
    'status' => 'active'
]);
$newUser->save();  // Automatically sets createdDate & modifiedDate

// Smart updating with change tracking
$user->name = 'Admiral Nova';
$user->rank = 'Fleet Admiral';

// Check what's changed
if ($user->isDirty()) {
    $changes = $user->getDirtyAttributes();  // Get only changed fields
    $originalName = $user->getOriginal('name'); // Get original value

    if ($user->isDirtyAttribute('rank')) {   // Check specific field
        echo "Rank changed!";
    }

    $user->save();  // Save changes
}

// Utility methods
$userId = $user->getId();           // Get primary key value
$isNewRecord = $user->isNew();      // Check if it's a new record
$user->refresh();                   // Reload from database

// Delete records
$user->delete();   // Remove from database

// Convert to array for JSON APIs
$userData = $user->toArray();
echo json_encode($userData);
Complete Method Reference

Your Navigation Console

Every method in your expanded model toolkit, organized by mission type.

Discovery Methods
Static
find($id) Locate a single record by its primary key. Returns null if not found.
Static
findAll($conditions, $orderBy, $limit) Retrieve multiple records with optional filtering, sorting and limiting.
Static
findFirst($conditions) Get the first record matching your criteria. Perfect for unique lookups.
Static
findIn($column, $values, $orderBy) Find records where column value is in a given array. Perfect for multiple IDs.
Static
findLike($column, $pattern, $orderBy, $limit) Search records with LIKE patterns. Great for text searches.
Static
count($conditions) Count records matching conditions. Returns integer count.
Static
exists($conditions) Check if records exist with given conditions. Returns boolean.
Modification Methods
Instance
save() Persist the model (insert if new, update if existing). Handles timestamps automatically.
Instance
delete() Remove the record from the database. Cannot be undone.
Instance
fill($attributes) Mass-assign attributes to the model from an associative array.
Quick Tip

All modification methods automatically handle timestamps and change tracking for you.

Inspection Methods
Instance
isDirty() Check if the model has unsaved changes since last save or load.
Instance
isDirtyAttribute($key) Check if a specific attribute has changed since last save.
Instance
getDirtyAttributes() Get array of only the attributes that have changed.
Instance
getOriginal($key) Get the original value of an attribute before any changes.
Instance
toArray() Convert the model to an associative array. Perfect for JSON APIs.
Instance
getId() Get the primary key value of the model.
Instance
isNew() Check if this is a new record that hasn't been saved yet.
Instance
refresh() Reload the model data from the database, discarding unsaved changes.
Magic Methods
Magic
__get($key) Access attributes like properties: $user->name
Magic
__set($key, $value) Set attributes like properties: $user->name = 'Nova'
Magic
__isset($key) Check if an attribute exists: isset($user->name)
Magic Methods

These methods make your models feel like native PHP objects with seamless property access.