Luminova Framework

PHP Luminova: Abstract Base Class for Database Models

Last updated: 2026-10-05 08:58:53

Base Model, allows you to define database models for your application, it also supports database searching using a third-party library provided by the Luminova team.

The database Base Model serves as the foundation for all models within your application, providing essential functionalities and features to interact with the database in an efficient and secure method.

It allows you to define basic rules for your Database Query Models, like fields that are allowed to be inserted into the model database table, delete, or update. Additionally, it also supports flagging the model as read-only which limits the model to only perform select statements.

Note:

Database query operations (insert, update, find, select, search, delete, total, count, exists, all, create, deleteMany, deleteAll, table, query, where) are implemented on Luminova\Database\Query\Helpers\QueryModel and forwarded automatically to your model instance through method overloading (__call/__callStatic). From your model's perspective, they behave as native methods.


Usage Examples

The following examples demonstrate how to use the Luminova model to interact with a database table. Every example below is driven from the single Customers model defined in Extending Model.

Because query operations (find, select, all, search, insert, create, update, delete, deleteMany, deleteAll, exists, count, total, table, query, where) are forwarded through __call/__callStatic, every one of them can be called either:

  • Statically — Customers::find(1) — a temporary instance is created internally for you, or
  • On an instance — (new Customers())->find(1) — useful when you need to keep working with the same model instance (e.g. to read getLastInsertedId(), chain sync(), or reuse a set identifier).

Both styles execute the same underlying query and are interchangeable unless otherwise noted.


Extending Model

The Customers model represents the customers data stored in the database customers table. This is the single model class all examples on this page reuse.

// File: /app/Models/Customers.php

namespace App\Models;

use Luminova\Base\Model;

class Customers extends Model
{
    /**
     * The table associated with the model.
     */
    protected string $table = 'customers';

    /**
     * The primary key for the table.
     */
    protected string $primaryKey = 'id';

    /**
     * Columns allowed during insert operations.
     */
    protected array $insertable = ['id', 'name', 'email', 'status'];

    /**
     * Columns allowed during update operations.
     */
    protected array $updatable = ['name', 'email', 'status'];

    /**
     * Columns searchable via search().
     */
    protected array $searchable = ['name', 'email'];

    /**
     * Enable query result caching.
     */
    protected bool $cacheable = true;
}

Retrieving a Record

find() retrieves a record by its primary key and returns the specified columns (defaults to $columns when omitted).

StyleExample
Static$customer = Customers::find(...);
Object$customer = (new Customers())->find(...);
use App\Models\Customers;

// Static style
$customer = Customers::find(1);

if ($customer) {
    echo "Customer Name: " . $customer->name . "\n";
    echo "Customer Email: " . $customer->email . "\n";
} else {
    echo "No customer found with ID 1.\n";
}
use App\Models\Customers;

// Object style
$customers = new Customers();
$customer = $customers->find(1);

Selecting Records

select() retrieves one or more records, optionally filtered by identifier(s).

StyleExample
StaticCustomers::select(...);
Object(new Customers())->select(...);
use App\Models\Customers;

// Static style: select specific customers by id
$rows = Customers::select([1, 2, 3], limit: 10, offset: 0);
use App\Models\Customers;

// Object style: select specific customers by id
$customers = new Customers();
$rows = $customers->select([1, 2, 3], limit: 10, offset: 0);

Selecting All Records

all() returns every matching record wrapped in a Collection.

StyleExample
StaticCustomers::all(...);
Object(new Customers())->all(...);
use App\Models\Customers;

// Static style
$all = Customers::all(limit: 50);

$all->each(function(mixed $item, string|int $name): void {
    echo $item->name . "\n";
});
use App\Models\Customers;

// Object style
$customers = new Customers();

$all = $customers->all(limit: 50);

$all->isEmpty();
$all->count();

Searching Records

search() matches against the columns configured in $searchable.

StyleExample
StaticCustomers::search(...);
Object(new Customers())->search(...);
use App\Models\Customers;

// Static style
$results = Customers::search('peter ujah', splitKeyword: true);
use App\Models\Customers;

// Object style
$customers = new Customers();
$results = $customers->search('peter ujah', splitKeyword: true);

Inserting Records

insert() accepts a single row or a nested array of rows.

StyleExample
StaticCustomers::insert(...);
Object(new Customers())->insert(...);

Batch insert, then read the last inserted id

use App\Models\Customers;

// Static style
Customers::insert([
    ['name' => 'Peter Ujah', 'email' => '[email protected]'],
    ['name' => 'Jane Doe', 'email' => '[email protected]'],
]);
use App\Models\Customers;

// Object style
$customers = new Customers();

$customers->insert([
    ['name' => 'Peter Ujah', 'email' => '[email protected]'],
    ['name' => 'Jane Doe', 'email' => '[email protected]'],
]);

echo $customers->getLastInsertedId();

Creating a Record

Unlike insert(), create() accepts only a single associative array, requires a primary key (or an already-set model identifier), and synchronizes the created record back onto the model — which is why create() is best used in object style.

use App\Models\Customers;

// Object style (recommended): the returned instance carries the synced attributes
$customers = new Customers();

$customer = $customers->create([
    'id' => 2,
    'name' => 'Jane',
    'email' => '[email protected]',
]);

if ($customer instanceof Customers) {
    echo $customer->name;
}
use App\Models\Customers;

// Static style: returns a new, separate synced instance
$customer = Customers::create([
    'id' => 3,
    'name' => 'Mark',
    'email' => '[email protected]',
]);

Updating Records

update() returns the synchronized model instance (?static) on success, or null when no matching record was updated.

StyleExample
StaticCustomers::update(...);
Object(new Customers())->update(...);
use App\Models\Customers;

// Static style
$updated = Customers::update(1, [
    'name' => 'Peter',
    'email' => '[email protected]',
]);
use App\Models\Customers;

// Object style: check existence first, then update using the model's identifier
$customers = new Customers(1);

if ($customers->exists()) {
    $updated = $customers->update(attributes: ['name' => 'Peter']);
}

Deleting Records

StyleExample
StaticCustomers::delete(...);
Object(new Customers())->delete(...);
Static (many)Customers::deleteMany(...);
use App\Models\Customers;

// Static style
Customers::delete(1);

// Delete multiple records
Customers::deleteMany([1, 2, 3]);
use App\Models\Customers;

// Object style: delete using the model's current identifier
$customers = new Customers(1);
$customers->delete();

// Delete multiple records
$customers->deleteMany([1, 2, 3]);

Custom Queries

Use table(), query(), or where() to drop down to the underlying query builder when the built-in CRUD helpers aren't enough.

StyleExample
StaticCustomers::where(...)->select(...);
Object(new Customers())->table()->where(...)->select(...);
use App\Models\Customers;

// Static style
$active = Customers::where('status', '=', 'active')
    ->get();

// ['id', 'name']
use App\Models\Customers;

// Object style
$customers = new Customers();

$active = $customers->table()
    ->where('status', '=', 'active')
    ->get();

Class Definition


Constants

ConstantValueDescription
TYPE_INSERT'insert'Operation type used when validating columns for insert queries.
TYPE_UPDATE'update'Operation type used when validating columns for update queries.
TYPE_SEARCH'search'Operation type used when validating columns for search queries.
TYPE_SELECT'select'Operation type used when validating columns selected from queries.
TYPE_ATTRIBUTE'attribute'Operation type used when validating model data attributes.
RETURN_SELF'self'Instructs setReturn()/$resultType to return query results as instances of the current model class.

Properties

table

Model database table name.

protected string $table = '';

primaryKey

The default primary key column name for the table. Used while selecting, updating, deleting, and more.

protected string $primaryKey = '';

searchable

Define your database table searchable columns, the fields that search() will look for matches in.

protected array<int,string> $searchable = []

cacheable

Enable or disable query result caching for select, find, all, search, total, count, or exists.

protected bool $cacheable = false;

expiry

Database cache expiration time TTL in seconds.

protected DateTimeInterface|int $expiry = 7 * 24 * 60 * 60;

readOnly

Specify whether the model's table is updatable, deletable, and insertable. When true, all write operations (insert, update, delete, deleteMany, deleteAll) are silently ignored and return false/null.

protected bool $readOnly = false

insertable

Define fields that can be inserted into.

protected array $insertable = []

updatable

Define fields that can be updated.

protected array $updatable = []

columns

Default columns selected when retrieving records via select(), find(), all(), where(), or search(), unless a custom column list is supplied to those methods.

protected array<int,string> $columns = ['*']

rules

Define your Input validation rules based on Luminova\Security\Validator and Luminova\Security\Rule class rules.

protected array<string,string> $rules = []

messages

Define your Input validation rules errors messages.

protected array<string,array> $messages = []

resultType

Query result hydration type. Supported values:

  • array — Returns associative arrays.
  • object — Returns standard objects.
  • self — Returns instances of the current model.
  • Any valid class name — Returns instances of the specified class.
protected string $resultType = self::RETURN_SELF;

Recommendation:

Use self::RETURN_SELF to always return an instance of the model class. Change it at runtime with setReturn().


allowIncludes

Allows direct PHP include/require statements within the model. When enabled, the debugger skips include/require enforcement for this model.

protected bool $allowIncludes = false;

Recommendation:

Keep this set to false unless direct includes are explicitly required. This allows the debugger to detect and report include/require usage within model classes, helping maintain a cleaner and more consistent codebase.

See Also:Luminova\Attributes\AllowIncludes — Class-level attribute #[AllowIncludes] for disabling include/require enforcement.


ignoredColumnAttributes

Model field column names excluded from assignment value to attribute during set() and synchronization via sync().

protected array<int,string> $ignoredColumnAttributes = [];

dbConnection

Database connection or driver instance assigned to the model. When null, the model uses the default configured database connection.

protected DatabaseInterface|Connection|null $dbConnection = null;

Set this using useConnection().


isSharedConnection

Indicates whether the assigned database connection is shared. A shared connection can be reused across model operations, while a non-shared connection is treated as dedicated to the current model instance.

protected bool $isSharedConnection = true;

Set this using useConnection().


identifier

Current model record identifier, used as the default identifier for find(), update(), and delete() when no identifier is explicitly provided. Assigned automatically after insert(), or manually via setIdentifier().

protected string|int|null $identifier = null;

persistentId

The cache folder/persistent identifier used to namespace this model's query cache. Generated automatically from the model class name when caching is enabled.

protected ?string $persistentId = null;

Methods

constructor

Initialize a model instance.

An optional identifier or attribute set may be provided. A scalar identifier is assigned to the model's primary key and becomes the current record identifier for find(), update(), and delete() when no identifier is given elsewhere. When an array or object is provided, its attributes are synchronized into the model.

public __construct(array|object|string|int|null $attributes = null)

Parameters:

ParameterTypeDescription
$attributesarray<string,mixed>|object{string:mixed}|string|int|nullOptional record identifier or initial model attributes.

Throw Exception:

\Luminova\Exceptions\InvalidArgumentException - Throws if the supplied attributes are not associative, or required primary-key data is missing.

Example - Create a model instance with an identifier:

$user = new User(100);
$user = $user->find();

Example - Create a model instance with attributes:

$user = new User([
    'id' => 100,
    'name' => 'John',
    'email' => '[email protected]',
]);

onCreate

Called during model initialization, immediately after the query handler is set up. Override this in a subclass to perform custom setup logic.

protected onCreate(): void

make

Create a model instance from existing record data.

The provided attributes are used to hydrate the model and must contain the configured primary key. This method is intended for existing database records where the record identity is required.

public static make(Model|array|object $attributes): static

Parameters:

ParameterTypeDescription
$attributesLuminova\Base\Model|array<string,mixed>|object{string:mixed}Existing model record data.

Return Value:

static - Return a new hydrated model instance.

Throw Exception:

\Luminova\Exceptions\InvalidArgumentException - If the attributes are empty, not associative, or missing the required primary key.

The attributes must contain the model primary key.


table

Creates a new query builder for the model's database table, pre-configured with the model's connection, caching, and result type settings.

public table(?string $alias = null): Luminova\Database\Query\Builder

Parameters:

ParameterTypeDescription
$aliasstring|nullOptional table alias.

Return Value:

Builder - Return a configured query builder instance.


query

Creates a new query builder from a raw SQL statement, pre-configured with the model's connection, caching, and result type settings.

public query(string $sql): Luminova\Database\Query\Builder

Parameters:

ParameterTypeDescription
$sqlstringRaw SQL query.

Return Value:

Builder - Return a configured query builder instance. Call execute() to run it.


where

Creates a new query builder with an initial WHERE condition, pre-selected with the model's configured columns.

public where(string $column, string $operation, mixed $value): Luminova\Database\Query\Builder

Parameters:

ParameterTypeDescription
$columnstringThe column name.
$operationstringComparison operator (e.g, =, !=, <, <>, etc).
$valuemixedValue to compare against.

Return Value:

Builder - Return a configured query builder instance.

Example:

Customers::where('age', '>', 18)
    ->and('country', '=', 'NG')
    ->get();

create

Creates a single record in the model's database table. Only a single associative array of column values is accepted. The created record's identifier is synchronized onto the model for subsequent operations such as find(), update(), and delete().

public create(array<string,mixed> $attributes): ?static

Parameters:

ParameterTypeDescription
$attributesarray<string,mixed>Associative array of column names and values.

Return Value:

static|null - Return the model instance if the record was created successfully, otherwise null.

Throw Exception:

\Luminova\Exceptions\RuntimeException - Throws if attributes are empty, a list array is passed (batch inserts are not supported here), the model has no resolvable primary key, or the data contains columns not allowed by $insertable.

Note: Attributes are synchronized with the current model after the record is created.


insert

Insert one or more records into the model's database table. Accepts either a single associative array, or an array of associative arrays for a batch insert. The inserted record's identifier is stored as the current model identifier when one isn't already set.

public insert(array|array $values): bool

Parameters:

ParameterTypeDescription
$valuesarray<string,mixed>|array<int,array<string,mixed>>Column-value pairs, or a nested array of rows to insert.

Return Value:

bool - Return true if one or more records were inserted, otherwise false. Also returns false immediately when $values is empty or the model is read-only.

Throw Exception:

\Luminova\Exceptions\RuntimeException - Throws if the insert values contain column names that aren't defined in $insertable.


update

Update the record matching the specified identifier. If no identifier is provided, the model's current identifier is used. Ignored when the model is read-only.

public update(string|int|null $identifier, array $attributes): ?static

Parameters:

ParameterTypeDescription
$identifierstring|int|nullRecord identifier. If null, the model's current identifier is used.
$attributesarray<string,mixed>Associative array of columns and values to update.

Return Value:

static|null - Return the model instance if the record was updated successfully, otherwise null (also returned when the model is read-only).

Throw Exception:

\Luminova\Exceptions\RuntimeException - Throws if no identifier is resolvable, or if the update data contains column names that aren't defined in $updatable.

Note: Attributes are synchronized with the current model after the record is updated.


find

Finds a single record by its primary key. If no identifier is provided, the model's current identifier is used.

public find(string|int|null $identifier = null, ?array $columns = null, ?string $cacheKey = null): mixed

Parameters:

ParameterTypeDescription
$identifierstring|int|nullRecord identifier. If null, the model's current identifier is used.
$columnsarray<int,string>|nullColumns to retrieve. Defaults to the model's configured $columns.
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

mixed - Return the matching record based on the configured result type, or null when no identifier is available.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


all

Selects all records from the model's database table.

public all(
    ?array $columns = null, 
    ?int $limit = null, 
    int $offset = 0, 
    ?string $cacheKey = null
): Luminova\Components\Collections\Collection

Parameters:

ParameterTypeDescription
$columnsarray<int,string>|nullColumns to retrieve. Defaults to the model's configured $columns.
$limitint|nullMaximum number of records to return. If null, no limit is applied.
$offsetintNumber of records to skip before returning results.
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

Collection - Return the selected records wrapped in a Collection.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


select

Select records from the model's database table, optionally filtered by primary key.

public select(
    string|int|array|null $identifier = null,
    ?array $columns = null,
    ?int $limit = 20,
    int $offset = 0,
    ?string $cacheKey = null
): mixed

Parameters:

ParameterTypeDescription
$identifierstring|int|array<int,mixed>|nullRecord identifier or list of identifiers. If null, all records are selected.
$columnsarray<int,string>|nullColumns to retrieve. Defaults to the model's configured $columns.
$limitint|nullSelect result limit (default: 20). If null, no limit is applied.
$offsetintSelect limit offset (default: 0).
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

mixed - Return selected records based on the configured result type, or false on failure.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


Searches records using the model's configured searchable columns ($searchable). Returns false immediately when the keyword is empty or no searchable columns are configured.

public search(
    string $keyword,
    ?array $columns = null,
    string $pattern = Builder::SEARCH_CONTAINS,
    bool $splitKeyword = false,
    bool $caseSensitive = false,
    int $limit = 100,
    int $offset = 0,
    ?string $collation = null,
    ?string $cacheKey = null
): mixed

Parameters:

ParameterTypeDescription
$keywordstringThe keyword or phrase to search for.
$columnsarray<int,string>|nullColumns to retrieve. Defaults to the model's configured $columns.
$patternstringSearch pattern to apply (default: Builder::SEARCH_CONTAINS).
$splitKeywordboolWhether to split a multi-word keyword into separate search terms.
$caseSensitiveboolWhether matching should consider character case.
$limitintMaximum number of records to return (default: 100).
$offsetintNumber of records to skip before returning results.
$collationstring|nullOptional comparison collation (e.g, utf8mb4_bin).
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

Collection|static|mixed - Return matching records wrapped in a Collection for multi-row results, or false when the keyword is empty or no searchable columns are configured.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if query execution fails.

Example - Search customers by configured searchable columns:

Customers::search('peter');

Example - Search with split keywords and case-sensitive matching:

Customers::search(
    'jane doe',
    splitKeyword: true,
    caseSensitive: true,
    collation: 'utf8mb4_bin'
);

delete

Deletes a single record from the model's table by primary key. If no identifier is provided, the current model identifier is used. When the deleted identifier matches the current model's identifier, the model's attributes are cleared. Ignored when the model is read-only.

public delete(string|int|null $identifier = null): bool

Parameters:

ParameterTypeDescription
$identifierstring|int|nullRecord identifier to delete. If null, the current model identifier is used.

Return Value:

bool - Return true if the record was deleted successfully, otherwise false.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.

See Also: purge() - To clear cache if any.


deleteMany

Deletes multiple records from the model's database table by a list of primary key identifiers. Ignored when the model is read-only.

public deleteMany(array $identifiers, ?int $limit = null): bool

Parameters:

ParameterTypeDescription
$identifiersarray<int,string|int>List of record identifiers to delete.
$limitint|nullMaximum number of records to delete.

Return Value:

bool - Return true if one or more records were deleted, otherwise false.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


deleteAll

Deletes all records from the model's database table. Ignored when the model is read-only.

public deleteAll(): bool

Return Value:

bool - Return true if one or more records were deleted, otherwise false.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


exists

Determines whether one or more records exist in the model's database table. If no identifier is provided, the current model identifier is used. Accepts a list of identifiers to check for any match.

public exists(array|string|int|null $identifier = null, ?string $cacheKey = null): bool

Parameters:

ParameterTypeDescription
$identifierarray<int,string|int>|string|int|nullRecord identifier or list of identifiers to check. If null, the current model identifier is used.
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

bool - Return true if matching record(s) exist, otherwise false.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


total

Gets the total number of unique records in the model's database table, counted by distinct primary key values.

public total(?string $cacheKey = null): int

Parameters:

ParameterTypeDescription
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

int - Return the number of unique records.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


count

Counts records in the model's database table. When an identifier or list of identifiers is provided, only matching records (by primary key) are counted.

public count(
    array|string|int|null $identifier = null,
    array|string $column = '*',
    bool $distinct = false,
    ?string $cacheKey = null
): int

Parameters:

ParameterTypeDescription
$identifierarray<int,string|int>|string|int|nullRecord identifier or list of identifiers to filter by primary key. If null, no identifier filter is applied.
$columnarray|stringThe column or columns to count (default: *).
$distinctboolWhether to count only distinct values.
$cacheKeystring|nullOptional cache key. If null, a stable cache key is generated automatically.

Return Value:

int - Return the number of matching records.

Throw Exception:

\Luminova\Exceptions\DatabaseException - Throws if the query fails.


purge

Clears cached query data associated with the current model's table.

public purge(): bool

Return Value:

bool - Return true if cached data was cleared successfully, or if caching isn't enabled for the model. Return false when a cache persistent identifier could not be resolved.


get

Retrieve an attribute value from the model.

public get(string $name, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$namestringAttribute name.
$defaultmixedDefault value returned when the attribute is missing.

Return Value:

mixed - Return the attribute value, or the default value when the attribute does not exist.


set

Set a model attribute value. Ignored (attribute silently skipped) if not allowed by canHydrateAttribute().

public set(string $name, mixed $value): self

Parameters:

ParameterTypeDescription
$namestringAttribute name.
$valuemixedAttribute value.

Return Value:

self - Return the current model instance.


has

Determine whether the model contains the specified attribute. Attributes with null values are considered present.

public has(string $name): bool

Parameters:

ParameterTypeDescription
$namestringAttribute name to check.

Return Value:

bool - Return true if the attribute exists, otherwise false.


hasIdentifier

Determine whether the model has a primary-key identifier set.

public final hasIdentifier(): bool

Return Value:

bool - Return true if the primary-key value is set, otherwise false.


values

Retrieve model attribute values with reset numeric keys.

public values(): array<int,mixed>

Return Value:

array<int,mixed> - Return the model attribute values.


keys

Retrieve all model attribute names.

public keys(): array<int,string>

Return Value:

array<int,string> - Return the list of attribute names.


scan

Find the first attribute value matching a callback condition.

public scan(callable(mixed,string):bool $callback): mixed

Parameters:

ParameterTypeDescription
$callbackcallable(mixed,string):boolCallback receiving the attribute value and name.

Return Value:

mixed - Return the first matching attribute value, or null when no attribute matches.


each

Execute a callback for each model attribute.

public each(callable(mixed,string):mixed $callback): static

Parameters:

ParameterTypeDescription
$callbackcallable(mixed,string):mixedCallback receiving the attribute value and name.

Return Value:

static - Return the current model instance for method chaining.


sync

Synchronize model attributes with the given data. Object properties are converted to an associative array first. Only allowed attributes (per canHydrateAttribute()) are updated.

public final sync(array|object $attributes): bool

Parameters:

ParameterTypeDescription
$attributesarray<string,mixed>|object{string:mixed}Source data used to update model attributes.

Return Value:

bool - Return true if at least one attribute was synchronized, otherwise false.

Throw Exception:

\Luminova\Exceptions\InvalidArgumentException - Throws if the attributes are not associative, or the primary key is missing for an unidentified model.


clearAttributes

Clears all model attributes while preserving the primary key value.

public final clearAttributes(): void

toArray

Convert the model attributes into an array.

public toArray(): array<int,mixed>

Return Value:

array<int,mixed> - Return the model attributes.


toObject

Convert the model attributes into a standard object.

public toObject(): object

Return Value:

object - Return an object containing the model attributes as properties.


jsonSerialize

Returns model data for JSON serialization.

public jsonSerialize(): array<string,mixed>

Return Value:

array<string,mixed> - Return the model attributes to encode as JSON.

Example:

class User extends Model {
    public function jsonSerialize(): array
    {
        $attributes = parent::jsonSerialize();
        unset($attributes['password']);

        return $attributes;
    }
}

isEmpty

Determine whether the model contains no attributes.

public isEmpty(): bool

Return Value:

bool - Return true when the model is empty, otherwise false.


isReadOnly

Check if the model's table is read-only.

public final isReadOnly(): bool

Return Value:

bool - Return true if is read only, otherwise false.


isSharedConnection

Determine whether the model uses a shared database connection.

public final isSharedConnection(): bool

Return Value:

bool - Return true when using a shared connection, otherwise false.


canHydrateAttribute

Determine whether a column can be hydrated as a model attribute.

Checks the configured ignored column attributes based on $ignoredColumnAttributes list. and returns false when the specified column is excluded from model attribute assignment.

public canHydrateAttribute(string $property): bool

Parameters:

ParameterTypeDescription
$propertystringDatabase column name to check.

Return Value:

bool - Return true if the attribute is allowed, otherwise false.


validateColumns

Determine whether columns are allowed for a specific operation type. When no allowed columns are configured for the operation, all columns are considered valid.

public validateColumns(
    array $columns, 
    string $type, 
    array &$unsupported = []
): bool

Parameters:

ParameterTypeDescription
$columnsarray<string,mixed>|array<int,string>Columns to validate. Associative arrays use their keys as column names.
$typestringOperation type: insert, update, search, select, or attribute (see: TYPE_*).
$unsupportedarray<int,string>Receives, by reference, columns that are not allowed.

Return Value:

bool - Return true when all columns are allowed, otherwise false.


assertColumnsAllowed

Assert that columns are allowed for the specified operation.

Ensures that columns are allowed for the specified operation, validates the provided column names against the configured allow list and throws an exception when unsupported columns are detected.

public final assertColumnsAllowed(array $columns, string $type): void

Parameters:

ParameterTypeDescription
$columnsarray<string,mixed>Column names and values to validate.
$typestringOperation type: insert, update, select, or search (see: TYPE_*).

Throw Exception:

\Luminova\Exceptions\RuntimeException - Throws if the columns contain unsupported keys.


useConnection

Set the database connection used by the model.

public useConnection(
    Luminova\Interface\DatabaseInterface|Luminova\Database\Connection $conn, 
    bool $shared = true
): self

Parameters:

ParameterTypeDescription
$connDatabaseInterface|ConnectionDatabase connection or driver instance.
$sharedboolWhether the connection is shared with other operations (default: true).

Return Value:

self - Return the current model instance.


setReturn

Set the database result hydration type.

public setReturn(string $returns): static

Parameters:

ParameterTypeDescription
$returnsstringResult type: array, object, self, or a valid class name.

Return Value:

static - Return the current model instance.

Recommendation: Use self::RETURN_SELF to always return an instance of the model class.


getConnection

Retrieve the database connection assigned to the model.

public final getConnection(): Luminova\Interface\DatabaseInterface|Luminova\Database\Connection|null

Return Value:

DatabaseInterface|Connection|null - Return the assigned connection instance, or null when no connection is set.


getLastInsertedId

Retrieve the last inserted id from the database after insert() (or create()) is called.

public getLastInsertedId(): mixed

Return Value:

mixed - Return the last inserted id from the database.


setIdentifier

Sets the current model record identifier.

public final setIdentifier(string|int $identifier): static

Parameters:

ParameterTypeDescription
$identifierstring|intRecord primary key value.

Return Value:

static - Return the current model instance.


getIdentifier

Retrieves the current model record identifier.

public final getIdentifier(): string|int|null

Return Value:

string|int|null - Return the current record identifier, or null when none has been assigned.


getCachePersistentId

Retrieve the persistent identifier used as the cache folder/namespace for this model.

public final getCachePersistentId(): ?string

Return Value:

string|null - Return the cache persistent identifier, or null when caching is disabled ($cacheable = false).


serialize

Serialize model attributes into a PHP serialized string.

public serialize(): string

Return Value:

string - Return the serialized model attributes.


unserialize

Restore model attributes from a PHP serialized string.

public unserialize(string $data): void

Parameters:

ParameterTypeDescription
$datastringSerialized model attributes.

Throw Exception:

\Luminova\Exceptions\UnexpectedValueException - Throws if the serialized data does not contain an array of model attributes.


Overriding Model Magic Methods

The model relies on PHP magic methods for core functionality. If you override these methods in a custom model, preserve the parent implementation unless you intentionally want to replace its behavior.

When adding custom behavior, you can call the parent method before or after your logic depending on the required behavior. For methods that provide a fallback mechanism, delegate to the parent when your custom logic does not handle the operation.

__construct()

Used to initialize the model. Call the parent constructor to preserve the model's internal initialization.

public function __construct(...$args)
{
    parent::__construct(...$args);

    // Custom initialization.
}

__get()

Handles access to inaccessible or undefined properties. Return your custom value when applicable; otherwise, delegate to the parent implementation.

public function __get(string $name): mixed
{
    if ($name === 'custom') {
        return $this->customValue;
    }

    return parent::__get($name);
}

__set()

Handles assignment to inaccessible or undefined properties. Handle custom properties in the child class and delegate all other properties to the parent.

public function __set(string $name, mixed $value): void
{
    if ($name === 'custom') {
        $this->customValue = $value;
        return;
    }

    parent::__set($name, $value);
}

__call()

Handles calls to inaccessible or undefined instance methods. Handle custom methods locally and delegate unresolved calls to the parent implementation.

public function __call(string $name, array $arguments): mixed
{
    if ($name === 'customMethod') {
        return $this->customMethod(...$arguments);
    }

    return parent::__call($name, $arguments);
}

__callStatic()

Handles calls to inaccessible or undefined static methods. Handle custom static methods locally and delegate unresolved calls to the parent implementation.

public static function __callStatic(string $name, array $arguments): mixed
{
    if ($name === 'customMethod') {
        return static::customMethod(...$arguments);
    }

    return parent::__callStatic($name, $arguments);
}

--

Calling the Parent Before or After

The parent method does not always have to be called at the same point. Choose the order based on whether the child logic should run before or after the model's built-in behavior.

Parent first:

public function __set(string $name, mixed $value): void
{
    parent::__set($name, $value);

    // Additional processing.
}

Custom logic first:

public function __set(string $name, mixed $value): void
{
    // Custom processing.

    parent::__set($name, $value);
}

Custom handling with parent fallback:

public function __call(string $name, array $arguments): mixed
{
    if ($name === 'customMethod') {
        return $this->customMethod(...$arguments);
    }

    return parent::__call($name, $arguments);
}

Warning:

Do not omit the parent call unless you intentionally want to replace the inherited behavior. In particular, omitting parent::__construct() can prevent the model from being properly initialized.